TypeScriptTypeScript16 min read

TypeScript Union Types

Understand union types to allow multiple possible types for a value and write flexible yet safe code.

David Miller
November 21, 2025
1.5k35

Union types let a variable hold more than one type.

  ## Why needed?
  In real apps, data is not always one shape.
  
  ## Example
  
  ```ts
  let id: number | string;
  
  id = 10;
  id = "A12";
  ```
  
  ## Using unions in functions
  
  ```ts
  function printId(id: number | string) {
    console.log(id);
  }
  ```
  
  ## Narrowing
  
  ```ts
  function printId(id: number | string) {
    if (typeof id === "string") {
      console.log(id.toUpperCase());
    } else {
      console.log(id.toFixed(2));
    }
  }
  ```
  
  ## With null
  
  ```ts
  let username: string | null = null;
  ```
  
  ## Graph
  
  ```mermaid
  flowchart TD
    A[Union Type] --> B[string]
    A --> C[number]
  ```
  
  ## Remember
  - Use unions for flexible APIs
  - Always narrow before using
  
#TypeScript#Beginner#Types