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

Typescript中如何将interface的属性类型转换为联合类型

TypeScript 实现方案

完全可以实现,使用 TypeScript 自带的索引访问类型即可直接达成需求。

你定义的原接口如下:

interface SomeType {
  abc: string;
  def: number;
  ghi: boolean;
}

只需要通过以下写法就能生成你需要的属性值类型联合:

type SomeOtherType = SomeType[keyof SomeType];

原理解释

  • keyof SomeType 会先返回 SomeType 所有属性名组成的联合类型,即 "abc" | "def" | "ghi"
  • 用属性名联合类型作为索引访问 SomeType,就会自动取出所有属性对应值的类型做联合,最终得到的 SomeOtherType 就是你需要的 string | number | boolean

你可以通过以下代码验证类型正确性:

// 合法赋值
const strVal: SomeOtherType = '测试字符串';
const numVal: SomeOtherType = 2024;
const boolVal: SomeOtherType = false;

// 非目标类型赋值会触发类型报错
const objVal: SomeOtherType = {};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 16:57:00