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

Ale*_*kex 2 typescript

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

const fruit = createFruit(['apple', 'orange']) // fruit is of type `string`
Run Code Online (Sandbox Code Playgroud)

我希望将 的类型fruit推断为字符串文字apple。难道就没有办法了吗?

Tob*_* S. 5

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

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

const fruit = createFruit(['apple', 'orange'])
//    ^? fruit: "apple"
Run Code Online (Sandbox Code Playgroud)

操场