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。难道就没有办法了吗?
对参数使用可变参数元组语法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)
| 归档时间: |
|
| 查看次数: |
93 次 |
| 最近记录: |