我有一种类型:

type To_String<N extends number> = `${N}`

我创建映射结果字符串号的类型:

type Remap<Number>
    = Number extends '0'
    ? 'is zero'
    : Number extends '1'
    ? 'is one'
    : Number extends '2'
    ? 'is two'
    : 'other number'

type One = Remap<To_String<1>> // 'is one'
type Other = Remap<To_String<5>> // 'other number'

到目前为止还不错,但随后我try 只传递‘number’,例如try 调用返回‘number’的函数,但在这里我不知道如何匹配以反标记显示的结果类型,并与字符串匹配:

type Remap<Number>
    // = Number extends `${number}` - attempt that catches all values
    = Number extends '${number}' // not matched against string version
    ? 'is Template literal result'
    : Number extends '1'
    ? 'is one'
    : Number extends '2'
    ? 'is two'
    : 'other number'

// this gives result type enclosed in backticks that still passes as string
type Template_String_Result = To_String<number> // `${number}`
// attempt that fails to catch top match clause
type Non_Literal_Number = Remap<To_String<number>>

有没有办法匹配这个模板文字字符串?

推荐答案

如果我没有理解错的话,您希望在第一个条件中使用​`${number}` extends Number,因为Number是一个泛型参数,所以它可能比${number}更宽(尽管在您的特定情况下不是这样).但如果我们把测试倒过来,那很好,因为任何匹配${number}的东西也会匹配比${number}更宽的东西.

type Remap<Number>
    = `${number}` extends Number
    ? "is Template literal result"
    : Number extends "1"
    ? "is one"
    : Number extends "2"
    ? "is two"
    : "other number"

然后你会得到这些结果,我认为这就是你想要的:

type One = Remap<To_String<1>>
//   ^? type One = "is one"
type Two = Remap<To_String<2>>
//   ^? type Two = "is two"
type Other = Remap<To_String<5>>
//   ^? type Other = "other number"
type Non_Literal_Number = Remap<To_String<number>>
//   ^? type Non_Literal_Number = "is Template Literal result"

Playground link

Typescript相关问答推荐

当类型断言函数返回假时,TypScript正在推断从不类型

泛型函数类型验证

为什么tsx不判断名称中有"—"的属性?'

在动态对话框中使用STEP组件实现布线

如何以Angular 形式显示验证错误消息

如何在Angular 12中创建DisplayBlock组件?

带switch 的函数的返回类型的类型缩小

如何调整对象 struct 复杂的脚本函数的泛型类型?

<;T扩展布尔值>;

专用路由组件不能从挂钩推断类型

为什么S struct 类型化(即鸭子类型化)需要非严格类型联合?

API文件夹内的工作员getAuth()帮助器返回:{UserID:空}

Angular 16将独立组件作为对话框加载,而不进行布线或预加载

在单独的组件中定义React Router路由

使用来自API调用的JSON数据的Angular

如何使用警告实现`RecursiveReadonly<;T>;`,如果`T`是原语,则返回`T`而不是`RecursiveReadonly<;T>;`

为什么受歧视的unions 在一种情况下运作良好,但在另一种非常类似的情况下却不起作用?

为什么类方法参数可以比接口参数窄

两个子组件共享控制权

在Nestjs中,向模块提供抽象类无法正常工作