I would like some explanation about this error I encounter:
interface Test {
a: number;
b: string;
c: string;
}
function f(obj1: Test, obj2: Test, field: keyof Test) {
obj1[field] = obj2[field]; // Error: Type 'string | number' is not assignable to type 'never'.
}
Here are some ways I found to circumvent that error:
- if Test contains only numbers or only strings
- if I use
obj1[field as string] = obj2[field]
- if I change my method to
function f<K extends keyof Test>(obj1: Test, obj2: Test, field: K)
But I don't understand why this code fails, is it a "bug" in typescript or am I missing something ?