0

我正在尝试定义一个接受字符串数组然后返回字符串的打字稿函数。该字符串保证是数组中的选项之一。我希望返回类型"string1" | "string2" | "string3"不仅仅是泛型string

这样调用函数的人可以在返回值上使用打字稿。

4

2 回答 2

1

从问题定义来看,您似乎正在尝试将array/tupleof 字符串转换为union-type. 其中一种方法是使用as const来实现这一点,可从version 3.4. 以下是示例代码 -

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-11T22:28:10.930 回答
0

使用联合类型:type myType = "string1" | "string2" | "string3"; 应该这样做

于 2020-10-11T15:59:16.620 回答