Start Coding

Topics

Union Types in TypeScript

Union types are a powerful feature in TypeScript that allow a variable to hold values of multiple types. They provide flexibility while maintaining type safety, making your code more robust and expressive.

What are Union Types?

A union type is a type formed from two or more other types, representing values that may be any one of those types. It's denoted using the pipe (|) symbol between the types.

Basic Syntax

Here's the basic syntax for declaring a union type:

let variable: Type1 | Type2 | Type3;

Common Use Cases

Union types are particularly useful in scenarios where a value could be one of several types. For example:

  • Functions that can accept different types of arguments
  • Variables that might hold different types of values
  • Return types that could vary based on conditions

Practical Examples

1. Variable with Multiple Types

let result: number | string;

result = 42;        // Valid
result = "success"; // Also valid
result = true;      // Error: Type 'boolean' is not assignable to type 'number | string'

2. Function with Union Type Parameter

function printId(id: number | string) {
    console.log("Your ID is: " + id);
}

printId(101);       // Valid
printId("202");     // Also valid
printId(true);      // Error: Argument of type 'boolean' is not assignable to parameter of type 'number | string'

Type Narrowing

When working with union types, TypeScript uses a technique called type narrowing to determine the specific type within a union. This is often done using type guards:

function padLeft(value: string, padding: string | number) {
    if (typeof padding === "number") {
        return " ".repeat(padding) + value;
    }
    return padding + value;
}

Best Practices

  • Use union types to create flexible, reusable code
  • Combine union types with Type Aliases for better readability
  • Be cautious with unions of complex types to avoid excessive type checking
  • Consider using Discriminated Unions for more complex scenarios

Related Concepts

To further enhance your understanding of TypeScript's type system, explore these related topics:

Union types are a cornerstone of TypeScript's type system, enabling developers to write more flexible and type-safe code. By mastering this concept, you'll be well-equipped to handle various scenarios in your TypeScript projects.