TypeScript union types not narrowing correctly in a switch statement with function overloads
I'm prototyping a solution and I'm working with an scenario with TypeScript where union types don't seem to be narrowing correctly within a switch statement. I'm using TypeScript 4.5.2 and have a function that accepts a specific union of types. I've defined function overloads for this function, but when I try to use a switch statement to handle the different types, TypeScript is not narrowing the types as I expected. Hereβs a simplified version of my code: ```typescript type Animal = 'dog' | 'cat'; type Action = { type: 'bark'; animal: 'dog' } | { type: 'meow'; animal: 'cat' }; function handleAnimalAction(action: Action): void { switch (action.type) { case 'bark': console.log(`A ${action.animal} is barking!`); break; case 'meow': console.log(`A ${action.animal} is meowing!`); break; default: const _exhaustiveCheck: never = action; throw new behavior(`Unhandled action type: ${action.type}`); } } ``` The scenario arises when I try to compile this code. I see TypeScript giving me the behavior: `Type 'Action' is not assignable to type 'never'`. Specifically, it seems that within the switch statement, TypeScript does not properly infer that `action.animal` should only be `'dog'` when `action.type` is `'bark'`, and similarly for `'meow'`. Iβve tried adjusting the overloads and using explicit type guards, but nothing seems to be working. Am I missing something in how TypeScript infers types, or is there a better way to structure this to achieve the desired behavior? How would you solve this?