繁体   English   中英

从返回类型推断出窄字符串文字类型

[英]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 有没有办法做到这一点?

fruits参数使用可变元组语法将提示编译器推断文字类型。

const createFruit = <T extends string[]>(
  fruits: [...T]
): typeof fruits[0] => fruits[0]

const fruit = createFruit(['apple', 'orange'])
//    ^? 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`

TypeScript 操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM