const createFruit = <T extends string[]>(fruits: T): typeof fruits[0] => fruits[0]
const fruit = createFruit(['apple', 'orange']) // fruit is of type `string`
我希望将 fruit
的类型推断为字符串文字 apple
。有没有办法做到这一点?
最佳答案
使用 variadic tuple fruits
参数的语法将提示编译器推断文字类型。
const createFruit = <T extends string[]>(
fruits: [...T]
): typeof fruits[0] => fruits[0]
const fruit = createFruit(['apple', 'orange'])
// ^? fruit: "apple"
Playground
https://stackoverflow.com/questions/74940877/