[英]Infer to a narrow string literal type from return type
const createFruit = <T extends string[]>(fruits: T): typeof fruits[0] => fruits[0]
const fruit = createFruit(['apple', 'orange']) // fruit is of type `string`
我希望将fruit
的类型推断为字符串文字apple
。 有没有办法做到这一点?
从 TS 5.0
开始,您将能够像这样在类型参数上使用const
修饰符:
const createFruit = <const T extends readonly string[]>(fruits: T): T[0] => fruits[0]
const fruit = createFruit(['apple', 'orange'])
目前可能的解决方案如下:
const createFruit = <N extends string, T extends N[] | []>(fruits: T): T[0] => fruits[0]
const fruit = createFruit(['apple', 'orange'])
在其中声明另一个类型参数N
以缩小从字符串到实际字符串类型文字的推断,然后将 T 的上限设置为T
T[] | []
T[] | []
,其中| []
| []
告诉 TS 推断元组类型而不是数组类型。
在这两种情况下,返回类型都可以简单地为T[0]
。
为了获得更强的类型以提供所需的行为,只需将参数键入为不可变数组,然后使用const
断言键入您作为参数传递的值:
const createFruit = <T extends readonly string[]>(fruits: T): typeof fruits[0] => fruits[0]
const fruit = createFruit(['apple', 'orange'] as const) // fruit is of type `apple`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.