Type System

TS Discriminated Unions

Using Discriminated Unions

TypeScript discriminated unions use literal types for safe switching.

What are Discriminated Unions?

Discriminated unions, also known as tagged unions or algebraic data types, are a powerful feature in TypeScript. They are used to model a variable that can hold multiple types of values but must conform to a specific set of rules defined by these types. A discriminated union is composed of multiple union members that share a common discriminant property.

Understanding the Discriminant Property

The discriminant property is a literal type that acts as a unique identifier for each member of the union. It is used by TypeScript to narrow down the possible types of a variable during runtime. Typically, the discriminant is a string literal, but it can also be a number or other literal type.

Safe Switching with Discriminated Unions

Using a discriminant property allows TypeScript to safely switch between different types within a union. The TypeScript compiler can ensure that all possible cases are handled, providing a safeguard against runtime errors. In the example above, the kind property is used to determine which code block to execute.

Exhaustiveness Checking

Exhaustiveness checking is a feature of TypeScript that ensures all cases in a switch statement are covered. If a new type is added to the union but not handled in the switch statement, TypeScript will issue an error.

In this example, if kind: 'triangle' is not handled, TypeScript will error out, ensuring that all possible shapes are accounted for.

Benefits of Using Discriminated Unions

Discriminated unions provide several benefits, including:

  • Type Safety: Ensures only the allowed types are used.
  • Readability: Code is easier to read and understand with clear types.
  • Maintainability: Adding new types or modifying existing ones is straightforward.

These features make discriminated unions an excellent choice for complex type scenarios.

Previous
Narrowing