LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
TypeScript

Union, Intersection & Literal Types

Basic types like string, number, and boolean are great for starting out, but real-world software is rarely that simple. An API response might return data or an error. A configuration flag might only allow three exact words. A database record might need fields from two different shapes combined together.

TypeScript – Union, Intersection & Literal Types

Basic types like string, number, and boolean are great for starting out, but real-world software is rarely that simple. An API response might return data or an error. A configuration flag might only allow three exact words. A database record might need fields from two different shapes combined together.

TypeScript solves this by letting you combine and restrict types using Unions (|), Intersections (&), and Literal Types. Together, these tools help you build rock-solid state machines and configuration flags that catch bugs before your code ever runs.

What you will learn
  • How Union Types (|) allow a value to be one of several types.
  • How Literal Types lock variables down to exact strings or numbers for configuration flags.
  • How Intersection Types (&) merge multiple object types into a single combined type.
  • How to combine Unions and Literals to build type-safe State Machines (Discriminated Unions).
  • Common mistakes to avoid and real interview questions senior engineers ask.

1. Quick Overview: Union vs Intersection vs Literal Types

Before writing code, think of these three features like everyday English words: OR, AND, and EXACTLY.

Feature Symbol Plain English Meaning Example
Union Type | This type OR that type string | number
Intersection Type & This type AND that type combined User & Timestamps
Literal Type Exact value EXACTLY this specific string or number "dark" | "light" or 200 | 404

2. Union Types (|) – Allowing Multiple Options

A Union Type lets a variable hold more than one type. You separate the allowed types with a vertical pipe (|). This is very common when dealing with user IDs, form inputs, or API responses where the data could arrive in two different formats.

Working with Union Types and Type Narrowing

When a variable has a union type, TypeScript only lets you use methods that exist on all types in the union. To use a string-specific or number-specific method, you first check the type using typeof. This is called type narrowing.

Example 1: Flexible Customer ID using Union Types

type CustomerId = string | number;

function formatCustomerId(id: CustomerId): string {
    if (typeof id === "string") {
        // TypeScript knows 'id' is a string here
        return `CUST-${id.toUpperCase()}`;
    }
    // TypeScript knows 'id' is a number here
    return `CUST-${id.toFixed(0)}`;
}

console.log(formatCustomerId("abc99"));
console.log(formatCustomerId(4021));

Expected output

CUST-ABC99
CUST-4021

3. Literal Types – Strict Configuration Flags

If you type a variable as string, a developer can pass "production", "prod", or even a typo like "prduction", and TypeScript won't complain. Literal types fix this by restricting a variable to exact string or numeric values.

This is the gold standard for configuration flags, theme settings, log levels, and HTTP status codes.

Example 2: String and Numeric Literals for Configuration Flags

type Environment = "development" | "staging" | "production";
type LogLevel = "debug" | "info" | "error";
type RetryCount = 0 | 1 | 3 | 5;

interface AppConfig {
    env: Environment;
    logLevel: LogLevel;
    maxRetries: RetryCount;
}

const serverConfig: AppConfig = {
    env: "production",
    logLevel: "error",
    maxRetries: 3
};

// serverConfig.env = "prod"; // Compile Error! Type '"prod"' is not assignable.
console.log(`Running in ${serverConfig.env} with ${serverConfig.maxRetries} retries.`);

Expected output

Running in production with 3 retries.
Important: Combining Literal Types with Unions ("development" | "staging" | "production") gives you autocomplete in VS Code and catches spelling mistakes immediately while you type—without adding any extra JavaScript code at runtime.

4. Intersection Types (&) – Combining Object Shapes

An Intersection Type combines multiple types into one. Using the ampersand (&), the resulting type has all properties from every type you combined. This is ideal for building modular, reusable building blocks in large applications.

Example 3: Combining Reusable Metadata with a User Profile

type Identifiable = {
    id: string;
};

type Auditable = {
    createdAt: string;
    updatedBy: string;
};

type UserProfile = {
    name: string;
    role: "admin" | "editor" | "viewer";
};

// Intersection: must have properties from ALL three types
type DatabaseUser = Identifiable & Auditable & UserProfile;

const adminUser: DatabaseUser = {
    id: "usr_101",
    name: "Anita",
    role: "admin",
    createdAt: "2026-11-19",
    updatedBy: "system"
};

console.log(`${adminUser.name} (${adminUser.role}) - ID: ${adminUser.id}`);

Expected output

Anita (admin) - ID: usr_101
Watch out: Never intersect two incompatible primitive types like type Impossible = string & number;. Because a value cannot be both a string and a number at the exact same time, TypeScript reduces it to the never type, making it unusable.

5. Architecture & Workflow Visualized: State Machines

In real-world frontend and backend systems, the most powerful use of Unions and Literals is building a State Machine using a pattern called a Discriminated Union.

Instead of tracking messy boolean flags like isLoading: true and hasError: true at the same time (which creates impossible states), you define each state as its own object with a shared literal property—usually called status.

API Request State Machine (Discriminated Union Flow)

Idle status: "idle" fetch() Loading status: "loading" 200 OK Success status: "success" + data 500 Fail Error status: "error" + message

Each box is a distinct type in a Union. Because every branch has a unique literal status, it is impossible to have both data and an error message at the same time.

6. Practical Example – Type-Safe State Machine in Action

Let's put Unions, Intersections, and Literal Types together into a single, production-ready API state handler.

Example 4: Handling an API State Machine with Switch

type RequestMeta = {
    requestId: string;
};

type ApiState =
    | ({ status: "idle" } & RequestMeta)
    | ({ status: "loading" } & RequestMeta)
    | ({ status: "success"; data: string[] } & RequestMeta)
    | ({ status: "error"; code: 400 | 404 | 500; message: string } & RequestMeta);

function renderState(state: ApiState): string {
    switch (state.status) {
        case "idle":
            return `[${state.requestId}] Waiting to start...`;
        case "loading":
            return `[${state.requestId}] Fetching data...`;
        case "success":
            return `[${state.requestId}] Loaded ${state.data.length} items.`;
        case "error":
            return `[${state.requestId}] Error ${state.code}: ${state.message}`;
    }
}

const currentState: ApiState = {
    requestId: "req_884",
    status: "success",
    data: ["Laptop", "Keyboard", "Mouse"]
};

console.log(renderState(currentState));

Expected output

[req_884] Loaded 3 items.

Step-by-Step Execution Breakdown

Step 1 (Intersection): Every state branch is intersected with RequestMeta, guaranteeing that state.requestId is always available no matter which state we are in.
Step 2 (Literal Discriminator): Each branch has a unique literal status ("idle", "loading", "success", "error").
Step 3 (Automatic Narrowing): Inside the switch statement, when state.status is "success", TypeScript automatically unlocks state.data. If you try to access state.message there, TypeScript stops you with a compile error.

7. Hands-On Practice

Try these exercises in VS Code or the TypeScript Playground to lock in what you learned.

Beginner Exercise 1: Traffic Light Literal Union

Create a type called TrafficLight that only allows "red", "yellow", or "green". Write a function that takes a TrafficLight and returns what a driver should do.

Hint: Use a switch statement on the literal values.

Intermediate Exercise 2: Feature Flag Config with Intersections

Create two types: BaseFeature (with name: string and enabled: boolean) and RolloutRule (with percentage: 10 | 25 | 50 | 100). Combine them using an intersection type called FeatureFlag.

Expected result: A valid FeatureFlag object that rejects invalid numbers like 33 for percentage.

Advanced Exercise 3: Payment State Machine

Design a Discriminated Union called PaymentState with three states: "pending" (no extra fields), "paid" (includes transactionId: string), and "failed" (includes reason: string). Write a function that prints a receipt or error message based on the state.

Hint: Use a shared status literal property on all three objects.

8. Interview Questions

Senior frontend and full-stack interviews frequently test how well you model domain data using TypeScript's type system.

Q1. What is the main difference between a Union (|) and an Intersection (&) type?

Answer: A Union (A | B) means a value can be either type A or type B. An Intersection (A & B) means a value must satisfy both type A and type B at the same time, combining all of their properties.

Q2. What happens if you create an intersection of two primitive types, like string & number?

Answer: TypeScript evaluates it to the never type. Because no value can simultaneously be a string and a number, it is an impossible type.

Q3. Why are Discriminated Unions better than boolean flags for state machines?

Answer: Boolean flags (like isLoading and isError) allow impossible states, such as both being true at once. A Discriminated Union uses a shared literal property (like status) so only one valid state can exist at a time, and TypeScript automatically narrows the available fields for each state.

Q4. When should you use a Literal Type union instead of a TypeScript enum?

Answer: Literal Type unions (like "asc" | "desc") are completely erased when compiled to JavaScript, meaning zero runtime overhead and smaller bundle sizes. They also work cleanly with plain JSON strings from APIs without needing to import an enum object.

Conclusion

Union, Intersection, and Literal types are the backbone of expressive TypeScript. By replacing vague string and boolean flags with exact literals and discriminated unions, you let the compiler catch logic bugs before your users ever see them.

Start applying these patterns to your API responses, configuration objects, and UI states. Your code will become easier to read, safer to refactor, and much more enjoyable to maintain.

Official Documentation

Upgradix by Shrash Studio – Learn Technology. Build Your Future.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.