A discriminated union, also known as a tagged union or variant type, is a powerful type system construct that allows you to define a type that can hold multiple different types of values, while also ensuring that you can safely determine which type is currently being used. This concept is particularly useful in TypeScript and other strongly typed languages, as it provides a way to handle complex data structures with varying shapes in a type-safe manner.
In TypeScript, a discriminated union is created by combining multiple types into a single type and using a common property, known as a "discriminant," to distinguish between them. This allows developers to leverage TypeScript's type-checking capabilities to ensure that the correct type is being used at any given time.
To define a discriminated union in TypeScript, you typically create an interface for each type and include a common property that acts as the discriminant. Here’s an example:
interface Circle {
kind: 'circle';
radius: number;
}
interface Square {
kind: 'square';
sideLength: number;
}
type Shape = Circle | Square;
Once you have defined a discriminated union, you can create a function that operates on the union type. TypeScript's type narrowing will allow you to safely access properties based on the discriminant:
function getArea(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius * shape.radius;
case 'square':
return shape.sideLength * shape.sideLength;
}
}
Discriminated unions are a powerful feature in TypeScript that enhance type safety and code clarity. By following best practices and avoiding common pitfalls, developers can effectively utilize this feature to manage complex data structures in a type-safe manner.