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
相关产品推荐
相关产品推荐

