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

