【发布时间】:2021-09-03 06:07:27
【问题描述】:
我在下面有一个基本的enum:
export enum Fruit {
apple,
banana
}
我想导出一个固定的Array enumkeys
export const Fruits = Object.entries(Fruit).map(f => f[0]);
应根据需要将['apple', 'banana'] 和Fruits 键入为string[]。
为了尝试更具体的打字,我添加了as keyof typeof Fruit,就像这样
export const Fruits = Object.entries(Fruit).map(f => f[0] as keyof typeof Fruit);
这给了我 type const Fruits: ("apple" | "banana")[]。 这是我能得到的最多的吗?
我的目标是获得像const Fruits: ["apple", "banana"] = .... 这样的打字,我认为这是我应该制作的完美打字。
脚注:
我不想使用定义enums 的其他方法,只是为了避免冗余,
export enum Fruit {
apple = 'apple',
banana = 'banana'
}
我很乐意做这样的事情:
interface Meal {
fruit: keyof tpeof Fruit // since the default enum values are integers, use keys
}
所以我很高兴有一个不需要我这样做的解决方案。如果没有其他办法,请在回答中提及。
【问题讨论】:
标签: typescript enums typing