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

TS中定义接口时如何保留隐式键名类型同时指定值类型

解决方案

方案1:使用TS 4.9+ 提供的satisfies操作符(推荐)

这是当前最优的实现方式,satisfies的作用是校验变量符合指定类型,同时不会拓宽变量的实际推导类型,完美匹配你的需求:

interface SpecialProperties {
  name: string;
  type: string;
}

const elements = {
  pirate: {
    name: 'patchy',
    type: 'matey'
  },
  captain: {
    name: 'peggy',
    type: 'pegleg'
  }
} satisfies Record<string, SpecialProperties>;

效果:

  • 所有对象值都会被强制校验必须符合SpecialProperties类型,缺少字段、字段类型错误都会触发TS报错
  • 变量elements的类型会保留所有实际定义的键(pirate、captain),其他模块导入使用时可以获得完整的智能提示,访问不存在的键会触发TS报错

方案2:低版本TS兼容方案:泛型工具函数

如果你使用的TS版本低于4.9,可以通过封装一个通用的泛型工具函数实现同样的效果:

interface SpecialProperties {
  name: string;
  type: string;
}

// 通用工具函数,约束所有值为SpecialProperties类型,同时保留键的字面量类型
const defineElementRecord = <K extends PropertyKey>(record: Record<K, SpecialProperties>) => record;

const elements = defineElementRecord({
  pirate: {
    name: 'patchy',
    type: 'matey'
  },
  captain: {
    name: 'peggy',
    type: 'pegleg'
  }
});

该方案的效果和satisfies完全一致。


内容的提问来源于stack exchange,提问作者crispEtomE

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:36:05