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’.
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
}