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

TypeScript报错:'{ [x: string]: number; }'无法赋值给'{ [K in Key]: 123; }'

TypeScript 泛型计算属性报错问题解析与解决

问题原因

当你在对象字面量中使用泛型变量key作为计算属性键时,TypeScript会触发类型拓宽行为:由于泛型Key extends string代表的是任意字符串子类型(而非具体的字面量类型),编译器无法在编译阶段确定Key的具体值,因此会将计算属性的索引类型自动放宽为string。这就导致返回对象的类型被推断为{ [x: string]: number },和函数声明的返回类型{ [K in Key]: 123 }不兼容,从而抛出类型不匹配的错误。

非类型断言的解决方案

方案1:封装通用工具函数

将对象创建逻辑封装到一个通用工具函数中,内部仅使用一次类型断言,对外提供干净的接口,避免业务代码中直接写断言:

function createKeyedObject<Key extends string, Value>(key: Key, value: Value): { [K in Key]: Value } {
  return { [key]: value } as { [K in Key]: Value };
}

function hello<Key extends string>(key: Key): { [K in Key]: 123 } {
  return createKeyedObject(key, 123);
}

hello<'myKey'>('myKey'); // 正常编译

方案2:利用Partial分步赋值(严谨型转换)

通过Partial类型先声明一个可选属性的对象,赋值后再完成类型收窄,这种转换比直接断言更安全,因为我们已确保所有必填属性都已赋值:

function hello<Key extends string>(key: Key): { [K in Key]: 123 } {
  const result: Partial<{ [K in Key]: 123 }> = {};
  result[key] = 123;
  return result as { [K in Key]: 123 };
}

内容的提问来源于stack exchange,提问作者Page not found

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:05:12