TypeScript
Summary - Discriminated unions
Write an event handler with discriminated unions.
Summary - Discriminated unions
Discriminated unions are ideal for modeling different events in a data flow under a single type. Each event is distinguished by its own discriminant value; a switch statement provides safe branching. When a new event is added, all cases must be updated, so the compiler catches gaps.
type Action =
| { type: "add"; item: string }
| { type: "remove"; id: number }
| { type: "clear" };
function apply(a: Action): string {
switch (a.type) {
case "add": return `added ${a.item}`;
case "remove": return `removed ${a.id}`;
case "clear": return "cleared";
}
}
Exercise Write an event handler
Define the Action discriminated union type: "add" (item: string), "remove" (id: number), "clear" members, with a type discriminant field. Write an apply(a: Action): string function using switch (a.type). For add return `added ${a.item}`, for remove return `removed ${a.id}`, for clear return "cleared". Print results via console.log(apply({ type: "add", item: "apple" })), console.log(apply({ type: "remove", id: 7 })), and console.log(apply({ type: "clear" })).
Show example solution
type Action =
| { type: "add"; item: string }
| { type: "remove"; id: number }
| { type: "clear" };
function apply(a: Action): string {
switch (a.type) {
case "add":
return `added ${a.item}`;
case "remove":
return `removed ${a.id}`;
case "clear":
return "cleared";
}
}
console.log(apply({ type: "add", item: "apple" }));
console.log(apply({ type: "remove", id: 7 }));
console.log(apply({ type: "clear" }));
Test yourself
-
What happens when a new member is added to a discriminated union?
- A runtime error is thrown
- If switch cases are missing, the compiler warns
- The union becomes an array
- Existing cases are updated automatically
Show answer
If switch cases are missing, the compiler warns — When a new member is added, the switch cases no longer cover all members; TypeScript warns about the missing case at compile time and provides safety.
-
Handle the clear event
type Action =
| { type: "add"; item: string }
| { type: "remove"; id: number }
| { type: "clear" };
function apply(a: Action): string {
switch (a.type) {
case "add": return `added ${a.item}`;
case "remove": return `removed ${a.id}`;
case ____: return "cleared";
}
}
Show answer
type Action =
| { type: "add"; item: string }
| { type: "remove"; id: number }
| { type: "clear" };
function apply(a: Action): string {
switch (a.type) {
case "add": return `added ${a.item}`;
case "remove": return `removed ${a.id}`;
case "clear": return "cleared";
}
}
-
Discriminated unions summary matching
- Discriminated union
- tagged member union
- Discriminant alan
- different literal value in each member
- switch ifadesi
- branch per member
- Yeni üye ekleme
- compiler catches missing case
Next lesson: Exhaustive with never