【发布时间】:2022-02-12 08:08:55
【问题描述】:
鉴于此枚举:
export enum Example {
First = 'A',
Second = 'B'
}
有没有办法构造一个类型为'A' | 'B'的类型?
我知道keyof typeof Example 会得到我'First' | 'Second',但我想要的是值,而不是键。
用例是我们在客户端的代码中有枚举。这些值作为 JSON 中的字符串从服务器向下发送。我想将 JSON 有效负载键入为接口,但将属性键入为字符串以匹配枚举值。
我意识到我可以这样做:
export interface Payload {
someProp?: Example;
}
但是在单元测试中,我们不能简单地将有效负载复制到 Typescript 中而不会出错:
const examplePayload: Payload = { someProp: 'A' }
导致错误:
Type '"A"' is not assignable to type 'Example | undefined'.ts(2322)
所以我想允许它成为枚举的值,但如果没有像这样对其进行硬编码,那么当枚举更改且类型未更改时会导致维护问题:
const examplePayload: Payload = { someProp: 'A' | 'B' }
不幸的是,我无法将其转换为字符串:
export type EnumValues<Type> = `${Type[keyof Type]}`;
const s: EnumValues<typeof Example>;
结果:
Type 'Type[keyof Type]' is not assignable to type 'string | number | bigint | boolean | null | undefined'.
我也不想在代码中使用'A' | 'B',因为服务器值并不总是很明显,使用枚举作为服务器有效值别名来维护代码要容易得多。
【问题讨论】:
标签: typescript