【发布时间】:2021-06-30 09:26:24
【问题描述】:
假设我有一个数组const a = ['apple', 'orange']。
基本上,我想将其转换为:
type MyType = 'apple' | 'orange';
我不知道 Typescript 是否可以做到这一点。我搜索了很多,但没有找到方法。
【问题讨论】:
标签: typescript
假设我有一个数组const a = ['apple', 'orange']。
基本上,我想将其转换为:
type MyType = 'apple' | 'orange';
我不知道 Typescript 是否可以做到这一点。我搜索了很多,但没有找到方法。
【问题讨论】:
标签: typescript
如果您只写const a = ['apple', 'orange'],编译器将推断a 的类型为string[],并且有关literal "apple" 或"orange" 值的任何信息都将丢失。这是合理的默认行为,因为人们经常希望从字符串数组中添加/删除 string 值。但这对您的用例没有帮助;它太宽了。您希望编译器为 a 推断出更窄的类型。
一种方法是使用const assertion:
const a = ['apple', 'orange'] as const;
// const a: readonly ["apple", "orange"]
现在编译器推断a 是文字字符串类型"apple" 和"orange" 的readonly tuple,按此顺序。
此时你有足够的信息来计算MyType:
type MyType = (typeof a)[number];
// type MyType = "apple" | "orange"
这是使用typeof type operator 查找a 的类型(即readonly ["apple", "orange"]),然后使用number 索引对其执行indexed access。由于(typeof a) 是一个数组类型,那么如果您使用number 对a 进行索引,您将获得"apple" 或"orange" 文字类型的值。因此,(typeof a)[number] 是 "apple" | "orange"。
【讨论】: