如何在TypeScript接口中使用变量作为键名?
解决TypeScript接口中使用动态计算属性键的问题
问题根源
TypeScript默认会把obj的属性值推断为宽泛的string类型,而接口中的计算属性键要求必须是字面量类型或唯一符号类型,这就是报错的原因。同时由于每个键对应不同类型,联合类型的索引签名无法满足需求。
解决方案
步骤1:将对象转为字面量类型断言
给obj添加as const断言,让TypeScript将每个属性值推断为具体的字符串字面量,而非通用string:
const obj = { name: 'name_key', details: 'details_key', profile: 'profile_key', } as const;
步骤2:用类型别名定义目标结构
由于接口不支持动态非字面量的计算属性定义,改用type类型别名即可直接使用obj的属性作为键名:
// 先定义自定义接口 interface DetailsInterface { /* 你的接口结构 */ } interface ProfileInterface { /* 你的接口结构 */ } type User = { [obj.name]: string; [obj.details]: DetailsInterface; [obj.profile]: ProfileInterface; };
大型对象优化方案:映射类型
如果obj是包含大量键的大型对象,手动逐个定义键值对过于繁琐,可以用映射类型自动关联键与对应类型:
const obj = { name: 'name_key', details: 'details_key', profile: 'profile_key', // 更多键... } as const; interface DetailsInterface { /* ... */ } interface ProfileInterface { /* ... */ } // 先定义原键名到类型的映射关系 type KeyTypeMap = { name: string; details: DetailsInterface; profile: ProfileInterface; // 对应更多键的类型... }; // 通过映射生成最终的User类型 type User = { [K in keyof typeof obj as typeof obj[K]]: KeyTypeMap[K]; };
最终生成的User类型会准确对应:
{ name_key: string; details_key: DetailsInterface; profile_key: ProfileInterface; }
内容的提问来源于stack exchange,提问作者Manish Rathod
相关产品推荐
相关产品推荐

