如何避免索引访问时出现TS2322:Type any is not assignable to type never错误
解决TypeScript中
Type any is not assignable to type never编译错误 错误原因
当attrName的类型为keyof MyInterface时,TypeScript无法确定它具体指向MyInterface的哪个属性,因此o[attrName]的类型会被推断为string | number的联合类型。而attrValue设为any时,TypeScript无法保证其类型与目标属性匹配,触发严格类型检查报错。
解决方案
1. 泛型约束(推荐)
通过泛型将attrName和attrValue的类型绑定,确保传入的属性值与目标属性类型完全匹配:
interface MyInterface { a: string; b: number; } function modify<K extends keyof MyInterface>(o: MyInterface, attrName: K, attrValue: MyInterface[K]) { o[attrName] = attrValue; }
这种方式让TypeScript能准确推断类型,既保留类型安全,又不会限制函数的灵活性。
2. 类型断言(谨慎使用)
如果能确保传入的attrValue类型正确,可以用类型断言绕过检查,但会失去TypeScript的类型保护:
interface MyInterface { a: string; b: number; } function modify(o: MyInterface, attrName: keyof MyInterface, attrValue: any) { o[attrName] = attrValue as MyInterface[typeof attrName]; }
3. 函数重载
为每个属性定义明确的重载签名,调用时TypeScript会检查参数类型匹配:
interface MyInterface { a: string; b: number; } function modify(o: MyInterface, attrName: "a", attrValue: string): void; function modify(o: MyInterface, attrName: "b", attrValue: number): void; function modify(o: MyInterface, attrName: keyof MyInterface, attrValue: any) { o[attrName] = attrValue; }
内容的提问来源于stack exchange,提问作者codeape
相关产品推荐
相关产品推荐

