如何从动态对象属性中获取动态联合类型。
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
对配置变量进行断言,以便将类型范围缩小到具体的字符串值
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)