When looking at this code, we see that the type of array is already specified. However, TypeScript throws an error when trying to push elements into the array, displaying the following message:
Argument of type 'string | number' is not assignable to parameter of type 'never'. Type 'string' is not assignable to type 'never'.
type Characters = {
letters: string[];
numbers: number[];
}
const characters :Characters = {
letters: ['a', 'b',' c' ],
numbers: [1,2,3],
}
type AddCharacter = <K extends keyof Characters, V extends Characters[K][number]>
(characterType:K, character:V) => void;
const addCharacter :AddCharacter = (characterType, character) =>{
characters[characterType].push(character) //Type 'string' is not assignable to type 'never'
}
addCharacter('letters', 'd') //ok
addCharacter('numbers', 4) //ok
addCharacter('letters', 4) //error as expected because 4 is not a string
addCharacter('numbers', 'd') //error as expected because 'd' is not a number
addCharacter('words', 'test' ) //error as expected because 'words' is not a key of 'Characters'
The reason behind the error in the code is unclear since the types seem correct with perfect type checking when calling addCharacter
.
Is there a way to resolve this error and make it work smoothly with TypeScript?
Thank you for any insights!
Playground