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

Why would TypeScript evaluate property of an object referenced by one of it's keys to be Never?

In the following simple example code that is assigning a value of type any to a property of an object referenced by a provided key, TypeScript is returning an error that suggests that the property is somehow never. The code:

type TypeAObject = {
  'first': string;
  'second': string;
  'third': number;
}

const assignKeyValue = (key: keyof TypeAObject, obj: TypeAObject, value: any) => {
  obj[key] = value; // Error: Type 'any' is not assignable to type 'never'.
}

This results in the following TypeScript error, seeming to suggest that obj[key] is never, even though key is explicitly keyof TypeAObject:

Error: Type ‘any’ is not assignable to type ‘never’.

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

I am running TypeScript 4.9.5.

This error can be seen at the following TypeScript playground:
https://www.typescriptlang.org/play?#code/C4TwDgpgBAKuEEEDyAjAVhAxsKBeKA3gFBRQDkAZgJYBOAzsGQFxQM1UB2A5gNwnl0sAew4ATZq2DtufUmWAALWuJYcArgFsUEGnwC+RIphEMoAQzp0qXDgGkIIAGpmANmuj4AFAGsHLXyBCFLDwyOhYwAA0UELoLHCQYRjY0QBuru4sZhwgAJR4AHyE-LFoANoBALp4UOluEPpAA

>Solution :

In your current implementation the obj[key] is resolved as string & number. Since string and number have nothing in common, the intersection results in never (empty set).

The right thing to do would be to use generics for the object, key and using these two you can determine the type of the value:

const assignKeyValue = <T extends TypeAObject, K extends keyof T>(key: K, obj: T, value: T[K]) => {
  obj[key] = value; // no error
}
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