Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix 'type is not assignable to any' when addressing a member

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You must make sure, that the val has the correct type that corresponds to the provided name.

Typescript Playground Example

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading