[英]Create Typescript Type from Enum values
I'm looking for a way to create a Typescript type from ENUM values.我正在寻找一种从 ENUM 值创建 Typescript 类型的方法。 Currently I'm having to manually construct the type and keep it in sync with the ENUM.目前我必须手动构造类型并使其与 ENUM 保持同步。
Is there a way to create a type as a oneof from ENUM values?有没有办法从 ENUM 值中创建一个类型作为一个类型? End result being when I update the ENUM the type will automatically reflect it最终结果是当我更新 ENUM 时,类型将自动反映它
enum FRUITS {
APPLE = 'apple',
PEAR = 'pear',
ORANGE = 'orange',
}
// type Fruits = FRUITS;
type Fruits = 'apple' | 'pear' | 'orange';
// This works
const fruit: Fruits = FRUITS.APPLE;
// This also works
const fruit2: Fruits = 'apple';
The type will be used in these scenarios so both have to still work:该类型将在这些场景中使用,因此两者都必须仍然有效:
const fruit: Fruits = FRUITS.APPLE;
const fruit2: Fruits = 'apple';
I always recommend staying away from enum
unless the values are truly opaque, meaning you do not need any TS code outside the enum declaration to refer to the number
/ string
as literal values.我总是建议从避而远之enum
,除非值是真正不透明的,这意味着你不需要枚举声明之外的任何TS码来指代number
/ string
为文字值。 (Actually I tend to stay away from numeric enum
entirely, since all number
values are assignable to them, see microsoft/TypeScript#17734 among other issues) (实际上我倾向于完全远离数字enum
,因为所有number
值都可以分配给它们,请参阅microsoft/TypeScript#17734以及其他问题)
For the specific use cases presented in your example, I'd be inclined to drop enum
and use a strongly-typed enumlike object instead:对于您的示例中提供的特定用例,我倾向于放弃enum
并使用强类型 enumlike 对象:
const FRUITS = {
APPLE: 'apple',
PEAR: 'pear',
ORANGE: 'orange',
} as const;
That allows Fruits
to be defined programmatically:这允许以编程方式定义Fruits
:
type Fruits = typeof FRUITS[keyof typeof FRUITS];
And then everything in your example still works:然后您示例中的所有内容仍然有效:
const fruit: Fruits = FRUITS.APPLE;
const fruit2: Fruits = 'apple';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.