Working with Discriminated Unions in TypeScript
Working with TypeScript's Discriminated Unions
Discriminated unions, also known as tagged unions, can be used to represent a type with multiple possibilities. Each possibility within a discriminated union has a unique tag, and the code can use the tag to determine which branch of the union to take. This technique allows for a compact and clear representation of complex types.
Creating a Discriminated Union in TypeScript
To create a discriminated union in TypeScript, begin by defining each of the possible branches of the union. For example:
type Person =
| { type: "student"; studentId: string }
| { type: "teacher"; teacherId: string };
This union consists of two possible types. The first type is for a student and contains only a student ID. The second type is for a teacher and contains only a teacher ID. The type property allows us to differentiate between these two possible types.
Using a Discriminated Union
Once we have defined our discriminated union, we can start using it. To illustrate how this works, let's assume that we have defined a function for getting a person's name:
function getName(person: Person): string {
switch (person.type) {
case "student":
return "John Doe (Student ID: " + person.studentId + ")";
case "teacher":
return "Jane Smith (Teacher ID: " + person.teacherId + ")";
}
}
In this example, the function takes a person as an argument and uses the type property to determine which branch of the discriminated union is being passed in. Depending on the type, it returns the appropriate name. This makes it easy to handle multiple types without having to write separate functions for each type.
Summary
Discriminated unions are a powerful tool for representing complex types in TypeScript. By giving each possibility a unique tag, it makes it easy to differentiate between the different branches of the union. This allows the code to make decisions based on which branch is being used. With discriminated unions, it's easy to handle multiple types without having to write a lot of extra code.