A discriminated union (also known as a tagged union or disjoint union) is a powerful feature in TypeScript that allows you to combine multiple types into a single type. It helps in representing a set of distinct possible cases where each case has uniquely identifiable properties. The discriminated union is a special kind of union type where one of the properties is used as a tag or discriminator to determine the specific type.
To create and use discriminated unions in TypeScript, you can follow these steps:
1. Define the types to be combined.
2. Add a common literal property (the tag) to differentiate each type.
3. Create a union type with the defined types.
4. Use type guards or switch-case statements to narrow down the specific type during runtime.
Let’s look at an example. Suppose we’re creating a graphics application with different shape objects like circles, rectangles, and triangles:
// Step 1: Define the types to be combined
interface Circle {
kind: 'circle'; // Step 2: Add a common literal property (the tag)
radius: number;
}
interface Rectangle {
kind: 'rectangle';
width: number;
height: number;
}
interface Triangle {
kind: 'triangle';
base: number;
height: number;
}
// Step 3: Create a union type with the defined types
type Shape = Circle | Rectangle | Triangle;
Now, we can have a function to compute the area of any given shape:
function getArea(shape: Shape): number {
// Step 4: Use type guards or switch-case statements
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'rectangle':
return shape.width * shape.height;
case 'triangle':
return 0.5 * shape.base * shape.height;
default:
// Ensures exhaustiveness checking at compile-time
const _exhaustiveCheck: never = shape;
return _exhaustiveCheck;
}
}
In this example, we first defined three types: ‘Circle‘, ‘Rectangle‘, and ‘Triangle‘. Then, added a common literal property ‘kind‘ with a different value for each type. Next, we defined a discriminated union type ‘Shape‘ using the combination of these types. Finally, we used a switch-case statement inside the ‘getArea‘ function to narrow down the specific type and computed the area of each shape separately.
The discriminated union feature of TypeScript comes in handy when you need to model and work with sets of distinct possible cases in a type-safe manner.