codez.guru

What is a Union Type?

A union type allows a value to be one of several types:

let input: string | number;

input = "hello";
input = 42;

Useful when a variable can take on multiple, known types.


Literal Types

Literal types are string, number, or boolean values themselves as types:

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

let state: Status = "success";

They’re perfect for enums, flags, and discriminated unions.


Type Narrowing with Unions

TypeScript smartly narrows the type based on runtime checks:

function printLength(value: string | string[]) {
  if (typeof value === "string") {
    return value.length;
  } else {
    return value.join(", ").length;
  }
}

This is called type narrowing β€” a core TypeScript feature.


What is an Intersection Type?

An intersection type combines multiple types into one:

type Timestamped = { createdAt: Date };
type User = { name: string };

type TimestampedUser = User & Timestamped;

const user: TimestampedUser = {
  name: "Sam",
  createdAt: new Date(),
};

All required fields from both types must be present.


Combining Unions and Intersections

You can build flexible and strict structures:

type Response =
  | { status: "success"; data: string }
  | { status: "error"; error: string };

Or combine behaviors:

type Loggable = { log: () => void };
type Savable = { save: () => void };

type Logger = Loggable & Savable;

Summary

  • Use union types to allow multiple possible types
  • Use literal types for specific value constraints
  • Use intersection types to merge multiple types into one
  • Leverage type narrowing with typeof, in, and instanceof for safety

Up next: Type Aliases vs Interfaces β€” when to use each and why.