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

如何在TypeScript接口中实现对象键的泛型定义

问题原因

TypeScript 中使用映射类型[P in K]构造对象类型时,泛型K必须是合法的对象键类型,默认没有给K加类型约束的情况下,编译器无法确认K符合索引签名的要求,就会抛出你遇到的报错。
合法的对象键类型固定为string | number | symbol,你可以用keyof any快速指代这个联合类型。

解决方案

方案1:给泛型K增加类型约束

// 增加 extends keyof any 约束,确认K是合法的键类型
interface SomeObj<K extends keyof any, V> {
  bar: {
    [P in K]: V
  }
};

const foo: SomeObj<string, number> = { 
  bar: {hello: 1234}
}

如果你的场景只允许字符串作为键,也可以直接把约束写为K extends string,还可以进一步限定具体的键字面量:

interface SomeObj<K extends string, V> {
  bar: {
    [P in K]: V
  }
};

// 仅允许hello、world两个键
const foo: SomeObj<'hello' | 'world', number> = { 
  bar: {hello: 1234, world: 5678}
}

方案2:直接使用内置的Record工具类型

TS 内置的Record工具类型就是封装好的映射类型,和你手写的[P in K]: V效果完全一致,代码更简洁:

interface SomeObj<K extends keyof any, V> {
  bar: Record<K, V>
};

const foo: SomeObj<string, number> = { 
  bar: {hello: 1234}
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:24:04