You need to enable JavaScript to run this app. Typescript 如何从动态对象属性中生成动态联合类型?
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:12:04