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

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/

相关文章:

c# - Blazor (.net 7) 中的三种依赖注入(inject)语法有区别吗?

python - 什么时候值得在 if-else 语句上使用循环?

javascript - 使用 js 正则表达式验证 gsheet/excel 相对范围字符串

c++ - 在 C++ 中有没有办法像在 Java 中那样进行垃圾回收?

powershell - 如何在 PowerShell 方法链接中使用换行符

regex - Linux 提取特定字符串之间的文本

r - 如何将整行作为列名?

c# - C# 是否有某种 value_or_execute 或 value_or_throw?

c# - 查找过去最近的日期

python - 捕获具有正面前瞻性但不匹配模式的组的正则表达式