使用索引访问时如何避免 TS2322“Type any is not assignable to type never”

问题描述 投票:0回答:2

给出以下代码:

interface MyInterface {
    a: string;
    b: number;
}

function modify(o: MyInterface, attrName: keyof MyInterface, attrValue: any) {
    o[attrName] = attrValue; // <-- typescript compiler error on this line
}

我在

TS2322: Type any is not assignable to type never
行收到打字稿编译器错误
t[attrName] = attrValue

如何避免此编译器错误?

typescript compiler-errors tsc
2个回答
1
投票

您可以使用类型断言告诉 TypeScript attrValue 的值与 t[attrName] 的类型兼容。一个例子是:

function modifyT(t: T, attrName: keyof T, attrValue: any) {
    t[attrName] = attrValue as T[keyof T]; // <-- no error
}

因此,如果您这样做,TypeScript 将假定 attrValue 是字符串或数字,具体取决于 attrName 的值,因此不会抱怨将 any 分配给 never。

除此之外,您还可以选择对 attrValue 使用泛型类型参数,并将其限制为 t[attrName] 的类型。一个例子是:

function modifyT<K extends keyof T>(t: T, attrName: K, attrValue: T[K]) {
    t[attrName] = attrValue; // <-- no error
}

如果这样做,TypeScript 将从 attrName 的类型推断出 attrValue 的类型,并确保它们兼容


1
投票

在函数上放置通用约束,并使用类型参数来限制

attrValue

interface MyInterface {
    a: string;
    b: number;
}

function modify<T, K extends keyof T>(t: T, attrName: K, attrValue: T[K]) {
    t[attrName] = attrValue;
}
© www.soinside.com 2019 - 2024. All rights reserved.