我正在尝试定义一个typescript函数,它接受一个字符串数组,然后返回一个字符串。该字符串被保证是数组中的一个选项。我希望返回类型为"string1" | "string2" | "string3",而不仅仅是泛型string。
这样,调用函数的人就可以对返回值使用typescript。
发布于 2020-10-12 06:28:11
从问题定义看,您似乎正在尝试将字符串的array/tuple转换为union-type。其中一种方法是使用version 3.4提供的as const来实现这一点。以下是示例代码-
const array = ['x', 'y', 'z'] as const;
type UnionType = typeof array[number]; // type "x" | "y" | "z"
const func = (input: typeof array): UnionType => {
return 'x';
};
console.log(func(['x', 'y', 'z']));发布于 2020-10-11 23:59:17
使用联合类型:应该这样做的type myType = "string1" | "string2" | "string3";
https://stackoverflow.com/questions/64305984
复制相似问题