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
相关产品推荐
相关产品推荐

