📘

Union and Intersection Types

Beginner
90 XP
35 min
Lesson Content

Union and Intersection Types

Union types allow a value to be one of several types, while intersection types combine multiple types.

Union Types

// Value can be string OR number
let id: string | number;
id = "123"; // OK
id = 123; // OK

// Function with union return
function getValue(): string | number {
  return Math.random() > 0.5 ? "hello" : 42;
}

Intersection Types

interface A {
  a: string;
}

interface B {
  b: number;
}

// Must have both A and B properties
let obj: A & B = {
  a: "hello",
  b: 42
};

Type Guards

function processValue(value: string | number): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return value.toString();
}
Example Code

Use union types for flexible values

function formatValue(value: string | number): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return `Number: ${value}`;
}

console.log(formatValue("hello"));
console.log(formatValue(42));

Expected Output:

HELLO
Number: 42
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code