TS Union Types

TypeScript Union Types

Union types are used when a value can realistically be more than a single type.

For instance, an ID could easily be a number or a string depending on the database.

Union types allow you to specify exactly which types are legally allowed.

This adds flexibility without sacrificing strict type safety.


1. Defining a Union Type

To define a union type, you use the pipe symbol (|) between the types.

It reads exactly like the logical "OR" operator in plain English.

It is incredibly useful for writing highly adaptable and reusable functions.

Union Type Example:

let statusCode: string | number;

statusCode = 200; // Perfectly valid statusCode = "OK"; // Also perfectly valid

// statusCode = true; // Error! boolean is not allowed.

console.log("Status Code:", statusCode);


2. Union Types in Functions

When using a union type in a function, you often need to check the actual type first.

This process is known as "Type Narrowing" and is essential for safety.

If you don't narrow the type, TypeScript restricts you to methods shared by both types.

Function Example:

function printId(id: number | string) {
  if (typeof id === "string") {
    console.log(id.toUpperCase()); // Safe to use string methods
  } else {
    console.log(id); // Must be a number here
  }
}

printId(101); printId("admin_user");


3. SEO and Flexibility

Union types prevent your application from breaking when handling unpredictable JSON responses.

Robust data handling leads to longer user sessions and lower bounce rates.

This technical stability signals high quality to search engine web crawlers.

Flexible Handling Example:

type Result = "success" | "error" | "loading";

let currentStatus: Result = "success"; // Restricts variables to very specific literal string values!

console.log("Current Status:", currentStatus);


Exercise

?

Which symbol is used to create a Union Type in TypeScript?


4. Final Thoughts

Union types make your code incredibly versatile without relying on any.

Always remember to use type narrowing when working with them inside functions.

Next up, we will deep dive into strongly typing your Functions!