TypeScript类方法修改对象属性时索引类型错误的解决问询
解决TypeScript中动态修改类对象属性的索引类型错误
错误代码示例
interface BackgroundProperties { color: string; image: string; opacity: number; } class Theme { data = { background: { color: '#fff', image: '', opacity: 1 } as BackgroundProperties }; setBackgroundProperty<K>(key: K, value: any) { // 报错:Type 'K' cannot be used to index type 'BackgroundProperties' this.data.background[key] = value; } }
错误原因
- 泛型
K没有任何约束,TypeScript无法确认它是BackgroundProperties的合法键名,自然不允许用它来索引该类型的对象。 value用any类型完全放弃了类型检查,不符合你“属性值类型严格匹配”的要求。
修复方案
给泛型K加上键名约束,同时让value的类型严格对应目标属性的类型:
interface BackgroundProperties { color: string; image: string; opacity: number; } class Theme { data = { background: { color: '#fff', image: '', opacity: 1 } as BackgroundProperties }; setBackgroundProperty<K extends keyof BackgroundProperties>( key: K, value: BackgroundProperties[K] ) { this.data.background[key] = value; } }
效果验证
调用方法时TypeScript会自动做类型校验:
const theme = new Theme(); theme.setBackgroundProperty('color', '#000'); // 合法,字符串匹配color的类型 theme.setBackgroundProperty('opacity', 0.5); // 合法,数字匹配opacity的类型 // 以下调用都会报错,符合预期 // theme.setBackgroundProperty('color', 123); // 数字不能赋值给string类型的color // theme.setBackgroundProperty('invalidKey', 'test'); // 不存在invalidKey这个属性
内容的提问来源于stack exchange,提问作者Pioupia
相关产品推荐
相关产品推荐

