如何将对象值作为TypeScript接口或状态的键?
TypeScript 用对象值作为接口键的解决方案
要实现把mainObject的值作为接口的键,你需要先让TypeScript识别到对象值的具体字面量类型,再用映射类型或索引类型来构建接口,步骤如下:
1. 修正mainObject的类型断言
默认情况下TypeScript会把mainObject的值推断为宽泛的string类型,加as const断言可以让它保留具体的字面量值:
export const mainObject = { NAME:'name', AGE:'age' } as const;
2. 生成目标接口
方式一:包含所有对象值作为键
先提取mainObject所有值的联合类型,再用映射类型生成接口:
import { mainObject } from './你的文件路径'; // 提取所有值的类型 type MainObjectValues = typeof mainObject[keyof typeof mainObject]; // 构建接口 interface Sample { [K in MainObjectValues]: string; }
最终生成的Sample接口效果:
interface Sample { 'name': string; 'age': string; }
方式二:只使用单个对象值作为键
如果只需要某一个值作为键,直接用索引类型即可:
import { mainObject } from './你的文件路径'; interface Sample { [typeof mainObject.NAME]: string; }
这样得到的接口就是:
interface Sample { 'name': string; }
内容的提问来源于stack exchange,提问作者Bhanu Prakash War
相关产品推荐
相关产品推荐

