Let's break down the issue at hand:
type Animal = 'dog' | 'cat';
type AnimalSound<T extends Animal> = T extends 'dog'
? 'woof'
: T extends 'cat'
? 'meow'
: never;
const animalSoundMap: {[K in Animal]: AnimalSound<K>} = {
dog: 'woof',
cat: 'meow',
};
const lookupSound = <T extends Animal>(animal: T): AnimalSound<T> => {
const sound = animalSoundMap[animal];
return sound;
}
The line with return
is throwing an error; apparently, the type of the sound
variable is resolved as 'woof' | 'meow'
, rather than being strictly typed as AnimalSound<T>
like one might expect. This raises the question - why isn't the typechecker happy about this?