[英]TypeScript: return a union of the input string array's literal values?
Can I type a function such that it takes a string[]
and the output is a string union?我可以输入一个 function 以便它需要一个string[]
并且 output 是一个字符串联合吗?
For example, given this function:例如,给定这个 function:
function myfn(strs: string[]) {
return strs[0];
}
If I call it like:如果我这样称呼它:
myfn(['a', 'b', 'c']) // => return type is: 'a' | 'b' | 'c'
Is this possible in TypeScript?这在 TypeScript 中是否可行?
You can add generic parameter to describe the array item, typescript will be able to infer it from provided value:您可以添加通用参数来描述数组项,typescript 将能够从提供的值推断它:
function myfn<T extends string>(strs: T[]) {
return strs[0];
}
const result = myfn(['a', 'b', 'c']) // "a" | "b" | "c"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.