You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从TypeScript类型的属性类型生成新联合类型?

解决方法

你可以通过索引访问类型结合keyof实现需求,写法为Person[keyof Person],它会自动提取Person类型所有属性的类型并组成联合类型。

示例代码:

type Person = {
  name: string,
  age: number,
  nicknames: string[],
}

// 最终得到 string | number | string[]
type PersonTypes = Person[keyof Person]

原理:

  • keyof Person会生成Person所有属性名的联合类型:"name" | "age" | "nicknames"
  • 用该联合类型作为索引访问Person,会取出每个属性对应的类型,最终合并为目标联合类型。

内容的提问来源于stack exchange,提问作者Paascuuu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 07:18:09