TypeScript泛型类如何限定索引类型仅为string或number?
解决TypeScript泛型类索引类型报错问题
你遇到的TS2536报错,核心原因是TypeScript无法确认泛型T属于合法的对象索引类型——TypeScript规定对象的索引签名只能是string、number或symbol类型。你需要给泛型T添加类型约束,限定它只能是string或number,既能解决报错,又能保证类型安全。
修改后的完整代码如下:
export class GenericClass<T extends string | number> { public selectionMap: {[id: T]: boolean} = {}; public isSelected(id: T): boolean { return !!this.selectionMap[id]; } public toggleSelected(id: T): void { if (this.isSelected(id)) { delete this.selectionMap[id]; } else { this.selectionMap[id] = true; } this.onChange(); } // 补充onChange方法定义(避免编译报错) private onChange(): void { // 这里编写你的业务逻辑 } }
关键说明:
T extends string | number:明确约束泛型T的范围,确保它只能是string或number类型,完全匹配你用它做索引的需求。- 添加约束后,TypeScript会认可
T是合法的索引类型,{[id: T]: boolean}的类型定义不再报错。 - 同时实现了类型安全:如果有人尝试用
boolean等不合法类型实例化GenericClass,TypeScript会直接抛出编译错误,避免运行时问题。
内容的提问来源于stack exchange,提问作者Andurit
相关产品推荐
相关产品推荐

