Typescript 如何从动态对象属性中生成动态联合类型?
解决方案
首先你需要先给原config对象添加as const断言,否则TypeScript会把数组默认推导为string[]类型,无法提取到具体的型号字面量:
const config = { devices: { Brand1: ['model1'], Brand2: ['model2', 'model3'], }, } as const; export type DeviceBrand = keyof typeof config.devices; // 'Brand1' | 'Brand2'
之后DeviceModel的类型定义如下:
export type DeviceModel = typeof config.devices[DeviceBrand][number]; // 'model1' | 'model2' | 'model3'
逻辑说明
typeof config.devices[DeviceBrand]会先拿到所有品牌对应型号数组的类型联合:readonly ["model1"] | readonly ["model2", "model3"]- 追加
[number]索引可以提取所有数组成员的类型,最终得到所有型号的字面量联合类型。
内容的提问来源于stack exchange,提问作者Rob Indesteege
相关产品推荐
相关产品推荐

