You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免索引访问时出现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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 02:20:03