Back

TypeScript Union Type

Union types allow variables to hold multiple types, useful for flexible data such as user inputs.

How to Define Union Types

let value: string | number;
value = "Hello";
value = 42;

The variable 'value' can be a string or number, allowing flexibility with type safety.

Real-World Scenario

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

API user IDs may be numbers or strings. Union types handle this variability with a single definition.

Using Type Guards

function handleInput(input: string | number) {
  if (typeof input === "string") {
    console.log("Text:", input.toUpperCase());
  } else {
    console.log("Number:", input.toFixed(2));
  }
}

Type guards like 'typeof' check the current type safely, handling each case appropriately.

Forms and User Inputs

let input: string | null = null;

Inputs may start as null, then become strings. Union types define these multiple states properly.

Why Use Union Types?

Union types provide both flexibility and safety when handling dynamic data, highlighting TypeScript’s strengths.

Back