在 TypeScript 中说一个变量是数组的成员
假设我有一个数组 const a=['apple', 'orange']。
基本上,我想把这个转换成类似这样的东西:
type MyType = 'apple' | 'orange';
我不知道使用 TypeScript 是否可能。我搜索了很多,但还没有找到方法。
答案#1
如果你只是写 const a=['apple', 'orange'],编译器会推断 a 的类型为 string[],关于字面量 "apple" 或 "orange" 的任何信息都会丢失。这是合理的默认行为,因为很多时候人们希望在字符串数组中添加或删除 string 值。但这对你的用例没有帮助;类型太广了。你希望编译器为 a 推断一个更窄的类型。
实现这一点的一种方法是使用 const 断言:
const a = ['apple', 'orange'] as const;
// const a: readonly ["apple", "orange"]
现在编译器推断 a 是按顺序包含字面量字符串类型 "apple" 和 "orange" 的只读元组。
此时你已经有足够的信息来计算 MyType:
type MyType = (typeof a)[number];
// type MyType = "apple" | "orange"
这是使用 typeof 类型操作符来查找 a 的类型(即 readonly ["apple", "orange"]),然后使用 number 索引对其进行索引访问。由于 (typeof a) 是数组类型,因此如果使用 number 对 a 进行索引访问,你将得到 "apple" 或 "orange" 字面量类型的值。因此,(typeof a)[number] 是 "apple" | "orange"。
代码的 Playground 链接
