如何基于TypeScript接口的类型动态创建新类型?
TypeScript 从接口值类型提取联合类型的解决方案
不需要依赖ts-essentials这类第三方工具,TypeScript原生的类型操作符就能直接实现需求:
- 保留你的原接口定义:
interface ITest { 0: number; 1: string; 2: boolean; 3: string; 4: string; 5: Date; 6: string; 7: boolean; 8: string; 9: string; 10: number; }
- 使用
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
相关产品推荐
相关产品推荐

