Union and Intersection Types: Combining Types

6 min read

Welcome back, Camper! ⛺️

By now, you are comfortable with basic types like string, number, and boolean. But let's be real—the real world is messy. Data coming from an API isn't always perfectly consistent. A variable might hold a number right now, but could be a string later. Or maybe you need to combine two different object definitions into one mega-object.

If we only used basic types, we’d be stuck writing duplicate code or, heaven forbid, using the forbidden any type (don't do it, I’m watching you 👀).

In this module, we are going to learn how to mix, match, and stitch types together using Unions and Intersections. Think of this as moving from painting with primary colors to mixing your own custom shades.


1. Union Types (|): Allowing Multiple Types

🛑 The Problem

Imagine you are writing a function that accepts an ID. In some databases, IDs are numbers (101). In others (like MongoDB), they are strings ("507f1f77bcf86cd799439011").

If you define your argument as number, string IDs will crash your build. If you define it as string, number IDs will fail.
You could use any, but then you lose all type safety, and the TypeScript compiler goes to a corner to cry.

✅ The Solution

Union Types allow a value to be one of several specific types. We use the vertical bar | (pipe character) to separate each type.

Definition: A Union Type describes a value that can be one of several types.

💻 Usage

typescript
// Define a type that can be a string OR a number
function printId(id: number | string) {
  console.log("Your ID is: " + id);
}

// Both of these work! 🎉
printId(101);
printId("202");

// This fails (as it should) 🛑
// printId({ myId: 101 }); // Error: Argument of type 'object' is not assignable...

🧠 Real World Analogy

Think of a Union Type like a payment terminal at a coffee shop. It accepts Cash | Card.

  • If you give it Cash, it works.
  • If you give it a Card, it works.
  • If you try to pay with a Live Chicken, it throws an Error.

2. Type Narrowing: Type Guards and typeof

🛑 The Problem

Unions are great, but they introduce a new problem. TypeScript is strictly logical. If a variable is string | number, TypeScript will only let you perform operations that are valid for BOTH strings and numbers.

typescript
function printId(id: number | string) {
  // Error! 💥
  // Property 'toUpperCase' does not exist on type 'number'.
  console.log(id.toUpperCase()); 
}

Even though we know id might be a string, TypeScript says, "What if it's a number? Numbers don't have uppercase letters. I cannot allow this risk."

✅ The Solution

Type Narrowing is the process of moving from a broad type to a specific type using logic checks. We use Type Guards to "guard" specific blocks of code. The most common guard for primitives is the JavaScript typeof operator.

💻 Usage

typescript
function printFormatId(id: number | string) {
  if (typeof id === "string") {
    // inside this block, TypeScript knows 'id' is ONLY a string
    console.log(`ID: ${id.toUpperCase()}`);
  } else {
    // inside this block, TypeScript implies 'id' must be a number
    console.log(`ID: ${id.toFixed(2)}`);
  }
}

printFormatId("abc"); // ID: ABC
printFormatId(100.1234); // ID: 100.12

🏭 Industry Standard: Early Returns

In professional codebases, we often use "Early Returns" to keep code clean.

typescript
function getLength(input: string | string[]) {
  if (Array.isArray(input)) {
    return input.length; // TS knows this is an array
  }
  
  // TS knows 'input' MUST be a string here, 
  // because the array case returned early.
  return input.length; 
}

3. Intersection Types (&): Merging Multiple Types

🛑 The Problem

Sometimes you have two separate Type definitions or Interfaces, and you need to create an object that contains properties from both.
For example, you have a Draggable type (x, y coordinates) and a Resizable type (width, height). You want to create a UI element that is both Draggable AND Resizable.

✅ The Solution

Intersection Types combine multiple types into one. This allows you to add together existing types to get a single type that has all the features you need. We use the ampersand & operator.

Definition: An Intersection Type creates a new type by combining all properties of existing types.

💻 Usage

typescript
type Draggable = {
  drag: () => void;
};

type Resizable = {
  resize: () => void;
};

// The Intersection 🤝
type UIWidget = Draggable & Resizable;

const box: UIWidget = {
  drag: () => console.log("Dragging..."),
  resize: () => console.log("Resizing..."),
  // If we miss one, TS yells at us.
};

🧠 Mental Model: Union vs Intersection

This often confuses people because of how we speak vs. logic.

  • Union (|): "OR" logic. The resulting value has a smaller set of guaranteed features (only the overlap).
  • Intersection (&): "AND" logic. The resulting value has a larger set of features (everything combined).

Warning: If you try to intersect incompatible types, you get never.
type Horror = string & number;
Nothing can be a string AND a number at the same time. This type becomes never (a black hole from which nothing returns).


4. Literal Types for Strict Value Control

🛑 The Problem

string is too broad. If you have a function move(direction: string), a user could pass "North", "north", "Up", or "KanyeWest". We want to restrict the variable to a specific set of exact values.

✅ The Solution

Literal Types allow you to specify the exact value a type must have. When combined with Union types, this becomes the most powerful tool for modeling application state (like Redux actions or API status).

💻 Usage

Basic Literal:

typescript
let strictName: "FreeCodeCamp" = "FreeCodeCamp";
// strictName = "SomethingElse"; // Error! 

The Power Move: Union of Literals (Enums alternative):
This is extremely common in React/Frontend development.

typescript
// Define exact allowed strings
type Alignment = "left" | "center" | "right";

function alignText(align: Alignment) {
  console.log("Aligning to: " + align);
}

alignText("center"); // ✅
// alignText("justify"); // ❌ Error: Argument '"justify"' is not assignable to 'Alignment'

🏭 Industry Practice: boolean vs. Literal Unions

Don't use booleans for complex states.

  • Bad: isLoading, isError, isSuccess (easy to get into impossible states like loading AND error).
  • Good: type Status = "idle" | "loading" | "success" | "error";

🕵️‍♀️ Discriminated Unions (The Holy Grail)

This combines everything we just learned. This is how you handle complex data structures in TypeScript.

typescript
type SuccessState = {
  status: "success"; // Literal
  data: string;
};

type ErrorState = {
  status: "error"; // Literal
  errorMsg: string;
};

type APIResponse = SuccessState | ErrorState; // Union

function handleResponse(response: APIResponse) {
  // We check the literal type "status"
  if (response.status === "success") {
    // TS knows 'response' is SuccessState here. We can access .data
    console.log(response.data); 
  } else {
    // TS knows 'response' is ErrorState here. We can access .errorMsg
    console.log(response.errorMsg);
  }
}

🧪 Summary

  1. Union (|): "I accept type A OR type B".
  2. Narrowing: Using typeof or logic to prove to TypeScript which specific type you are holding.
  3. Intersection (&): "I need type A AND type B combined".
  4. Literals: "I only accept these specific values".

🔗 Useful Links & References

Now, go fix those any types in your code! 🚀

Challenge

Challenge: Advanced Type Modeling for a Payment Gateway

You are tasked with building the type system for a payment processing gateway in TypeScript. The gateway must handle three distinct payment methods: Credit Card, PayPal, and Cryptocurrency. Your goal is to use advanced TypeScript features to create a robust, type-safe model that prevents invalid data structures.

Requirements:

  1. Base Transaction Type: Create a type alias TransactionDetails that includes properties common to all transactions: transactionId (a string) and amount (a number).

  2. Specific Payment Method Types: Create three distinct types representing the data needed for each payment method:

    • A type for Credit Card payments that includes a method literal set to "credit_card", plus cardNumber, expiryDate, and cvv (all strings).
    • A type for PayPal payments that includes a method literal set to "paypal", plus an email (string).
    • A type for Crypto payments that includes a method literal set to "crypto", plus a walletAddress (string) and a network which can only be "BTC" or "ETH".
  3. Composed Types using Intersection: Use an Intersection Type (&) to create three final, complete payment types (CreditCardPayment, PayPalPayment, CryptoPayment). Each of these should combine the TransactionDetails type with its corresponding specific payment method type from step 2.

  4. Master Payment Union Type: Create a Union Type (|) named Payment that can be any one of the three composed types from step 3.

  5. Type-Safe Processing Function: Implement the body of the processPayment function. This function accepts a single argument of type Payment. Inside the function, use a Discriminated Union pattern (by checking the method property) to safely access the properties specific to each payment method and log a descriptive string. The function should not produce any TypeScript errors.

Expected result

The final code should correctly define all the required types and implement the function body.

  1. TransactionDetails must be a type alias for an object with transactionId: string and amount: number.
  2. Three final composed types (CreditCardPayment, PayPalPayment, CryptoPayment) must be created using an intersection (&) of TransactionDetails and an object literal containing the method-specific properties.
    • CreditCardPayment must include method: "credit_card", cardNumber: string, expiryDate: string, and cvv: string.
    • PayPalPayment must include method: "paypal" and email: string.
    • CryptoPayment must include method: "crypto", walletAddress: string, and a literal union for network: "BTC" | "ETH".
  3. The Payment type must be a union (|) of CreditCardPayment, PayPalPayment, and CryptoPayment.
  4. The processPayment function must contain a switch statement (or equivalent if/else logic) that checks the payment.method property.
  5. Inside each case of the switch, the code must correctly access properties unique to that type without causing a TypeScript error (e.g., accessing payment.cardNumber inside the "credit_card" case, and payment.walletAddress inside the "crypto" case).
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.