Typescript 动态联合类型的动态对象属性

罗布·英德斯蒂格

如何从动态对象属性中获取动态联合类型。

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

您需要对constconfig 变量使用断言,以便将类型缩小到具体的字符串值

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章