TypeScript:返回输入字符串数组的文字值的并集吗? [英] TypeScript: return a union of the input string array's literal values?
本文介绍了TypeScript:返回输入字符串数组的文字值的并集吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以键入一个采用 string []
并且输出为字符串并集的函数吗?
Can I type a function such that it takes a string[]
and the output is a string union?
例如,给定此功能:
function myfn(strs: string[]) {
return strs[0];
}
如果我这样称呼它:
myfn(['a', 'b', 'c']) // => return type is: 'a' | 'b' | 'c'
在TypeScript中可以吗?
Is this possible in TypeScript?
推荐答案
您可以添加通用参数来描述数组项,打字稿将能够从提供的值中推断出它:
You can add generic parameter to describe the array item, typescript will be able to infer it from provided value:
function myfn<T extends string>(strs: T[]) {
return strs[0];
}
const result = myfn(['a', 'b', 'c']) // "a" | "b" | "c"
这篇关于TypeScript:返回输入字符串数组的文字值的并集吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文