I have a code like this:
interface IFoo {
bar: string;
baz: number;
}
function f(foo: IFoo, name: 'bar' | 'baz', val: any) {
foo[name] = val; // <<< error: Type 'any' is not assignable to type 'never'.
}
If I change the type of "baz" to be also "string" then the error is gone:
interface IFoo {
bar: string;
baz: string;
}
function f(foo: IFoo, name: 'bar' | 'baz', val: any) {
foo[name] = val; // fine
}
Why is this happening, and would it be possible to fix this?
I’m looking for a solution that is better than replacing name: 'bar' | 'baz' with name: string.
>Solution :
You must make sure, that the val has the correct type that corresponds to the provided name.
interface IFoo {
bar: string;
baz: number;
}
function f<K extends keyof IFoo>(foo: IFoo, name: K, val: IFoo[K]) {
foo[name] = val;
}
const foo: IFoo = {
bar: '',
baz: 0
}
f(foo, 'bar', 'abc')
f(foo, 'baz', 1)
console.log(foo);