如何从动态对象属性中获取动态联合类型。
const config = {
devices: {
Brand1: ['model1'],
Brand2: ['model2', 'model3'],
},
};
export type DeviceBrand = keyof typeof config.devices; // 'Brand1' | 'Brand2'
export type DeviceModel = ___________; // 'model1' | 'model2' | 'model3'
我需要做什么才能使 DeviceModel 成为对象中所有品牌的模型的联合类型?
干得好:
const config = {
devices: {
Brand1: ['model1'],
Brand2: ['model2', 'model3'],
},
} as const;
export type DeviceBrand = keyof typeof config.devices; // 'Brand1' | 'Brand2'
export type DeviceModel = typeof config['devices'][DeviceBrand][number]; // 'model1' | 'model2' | 'model3'
const a: DeviceModel = 'model1' // valid
const b: DeviceModel = 'model4' // type error
您需要对const
config 变量使用断言,以便将类型缩小到具体的字符串值
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句