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

如何基于TypeScript接口的类型动态创建新类型?

TypeScript 从接口值类型提取联合类型的解决方案

不需要依赖ts-essentials这类第三方工具,TypeScript原生的类型操作符就能直接实现需求:

  1. 保留你的原接口定义:
interface ITest {
    0: number;
    1: string;
    2: boolean;
    3: string;
    4: string;
    5: Date;
    6: string;
    7: boolean;
    8: string;
    9: string;
    10: number;
}
  1. 使用keyof和索引访问类型创建目标联合类型:
type ValueFromITest = ITest[keyof ITest];

原理说明

  • keyof ITest会生成接口所有键的联合类型:0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
  • 索引访问ITest[keyof ITest]会自动遍历所有键对应的值类型,并合并为去重后的联合类型,最终得到number | string | boolean | Date,完全符合需求。

内容的提问来源于stack exchange,提问作者Leonardo Petta do Nascimento

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 16:55:27