While utilizing all variations of a discriminated union with conditional if
statements in TypeScript, the type is narrowed down to the specific variant. To achieve the same effect by expressing the logic through a mapping from the discriminant to a function that processes the variant, it's essential to view the mapping as a distributive type rather than just a mapped type. Despite reading through resources like this Stack Overflow answer and this GitHub pull request, I'm still struggling to apply this concept to my own scenario.
type Message =
| { kind: "mood"; isHappy: boolean }
| { kind: "age"; value: number };
// Mapping structure example for reference
type Mapping = {
mood: (payload: { isHappy: boolean }) => void;
age: (payload: { value: number }) => void;
};
// Sample mapping object ensuring correct keys and signatures
const mapping: Mapping = {
mood: ({ isHappy }) => {
console.log(isHappy);
},
age: ({ value }) => {
console.log(value + 1);
},
};
// Function to process the message based on its kind
const process = (message: Message) => {
// Issue arises here as TypeScript cannot infer the right message type
mapping[message.kind](message);
};