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

如何将对象值作为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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 13:20:51