JavaScript and TypeScript course ยท Module 6: TypeScript Basics

Union and intersection types

9 min read ยท
In this lesson4

Welcome to the advanced TypeScript type laboratory in Jurassic Park! Dr. Henry Wu is especially excited today, because we will be discussing two powerful TypeScript mechanisms that can be compared to his most ambitious genetic engineering projects: union and intersection types.

Union Types - "either this or that"

A union type allows a variable to accept values of one of several different types. It's a bit like a hybrid enclosure in the park that can accommodate different species of dinosaurs, but only one kind at a time.

Basic syntax of union types

We create a union type using the | (pipe) operator:

// A variable can be of type string OR number
let dinosaurIdentifier: string | number;

dinosaurIdentifier = "TREX-01"; // Ok, string is allowed
dinosaurIdentifier = 12345;     // Ok, number is allowed
// dinosaurIdentifier = true;   // Error! boolean is not part of the union string | number

Practical applications of union types

Union types are extremely useful in many practical scenarios in Jurassic Park:

1. Handling different identifier formats

// Function that can accept different types of identifiers
function findDinosaur(id: string | number): void {
  // We must check the type before performing type-specific operations
  if (typeof id === "string") {
    console.log(`Looking for dinosaur with code: ${id.toUpperCase()}`);
  } else {
    console.log(`Looking for dinosaur with number: ${id.toFixed(0)}`);
  }
}

findDinosaur("RAPTOR-BLUE"); // "Looking for dinosaur with code: RAPTOR-BLUE"
findDinosaur(42);            // "Looking for dinosaur with number: 42"

2. Functions returning different types

// Function that can return a dinosaur or an error message
function getDinosaurData(id: string):
  { name: string; species: string; age: number } | string {

  // Simulating a database
  const database = new Map([
    ["TRex1", { name: "Rex", species: "Tyrannosaurus", age: 7 }],
    ["Rap1", { name: "Blue", species: "Velociraptor", age: 4 }]
  ]);

  const dinosaur = database.get(id);

  if (dinosaur) {
    return dinosaur; // Returns dinosaur object
  } else {
    return `Dinosaur with ID not found: ${id}`; // Returns error message
  }
}

const result = getDinosaurData("TRex1");
// We need to check the type of the returned value
if (typeof result === "string") {
  console.log(`Error: ${result}`);
} else {
  console.log(`Found: ${result.name}, species: ${result.species}`);
}

3. Handling optional parameters

// Function generating a report that can accept different filter parameters
function generateDinosaurReport(
  filter?: { species?: string; minAge?: number; predators?: boolean }
): string {
  let report = "Dinosaur report:\n";

  if (filter) {
    report += "Filters:";
    if (filter.species) report += ` Species=${filter.species}`;
    if (filter.minAge) report += ` MinAge=${filter.minAge}`;
    if (filter.predators !== undefined) report += ` OnlyPredators=${filter.predators}`;
  } else {
    report += "No filters - showing all dinosaurs";
  }

  return report;
}

console.log(generateDinosaurReport()); // Without filters
console.log(generateDinosaurReport({ species: "Velociraptor" })); // With species filter
console.log(generateDinosaurReport({ minAge: 5, predators: true })); // With multiple filters

Discriminated Unions

Discriminated unions are an advanced technique of using union types with a "discriminating property" that allows TypeScript to recognize which type we're dealing with. It's like the dinosaur identification system in the park, which immediately tells whether we're dealing with a herbivore or a predator.

// Defining interfaces with the discriminating property "type"
interface Herbivore {
  type: "herbivore";
  diet: string[];
  aggressionLevel: number; // 1-10
}

interface Predator {
  type: "predator";
  prey: string[];
  biteForce: number; // in PSI
}

// Type that is a union of two interfaces
type Dinosaur = Herbivore | Predator;

// Function using the discriminated union
function manageDinosaur(dino: Dinosaur): void {
  // We check the discriminating property
  switch (dino.type) {
    case "herbivore":
      // TypeScript knows that dino is of type Herbivore here
      console.log(`Prepare fodder: ${dino.diet.join(", ")}`);
      if (dino.aggressionLevel > 7) {
        console.log("Warning: Herbivore with high aggression level!");
      }
      break;
    case "predator":
      // TypeScript knows that dino is of type Predator here
      console.log(`Prepare meat for: ${dino.prey.join(", ")}`);
      if (dino.biteForce > 10000) {
        console.log("Warning: Very dangerous predator!");
      }
      break;
  }
}

// Usage examples
const triceratops: Herbivore = {
  type: "herbivore",
  diet: ["ferns", "cycads", "conifers"],
  aggressionLevel: 6
};

const tRex: Predator = {
  type: "predator",
  prey: ["triceratops", "edmontosaurus", "pachycephalosaurus"],
  biteForce: 12800
};

manageDinosaur(triceratops);
manageDinosaur(tRex);

Intersection Types - "both this and that"

An intersection type allows combining multiple types into one, more complex type. It's like Dr. Wu's experiments with combining DNA from different dinosaurs to create entirely new species with the traits of all "ingredients".

Basic syntax of intersection types

We create an intersection type using the & operator:

// Defining interfaces of basic traits
interface BasicDinosaur {
  id: number;
  name: string;
  species: string;
  age: number;
}

interface PhysicalTraits {
  height: number; // in meters
  length: number; // in meters
  weight: number;   // in kilograms
}

interface BehavioralTraits {
  aggressionLevel: number; // 1-10
  territorial: boolean;
  social: boolean;
}

// Creating a type that is the intersection of three interfaces
type FullDinosaurProfile = BasicDinosaur & PhysicalTraits & BehavioralTraits;

// Now the object must implement all properties from all three interfaces
const velociraptor: FullDinosaurProfile = {
  // From BasicDinosaur
  id: 101,
  name: "Blue",
  species: "Velociraptor",
  age: 4,

  // From PhysicalTraits
  height: 0.5,
  length: 2,
  weight: 15,

  // From BehavioralTraits
  aggressionLevel: 8,
  territorial: true,
  social: true
};

Practical applications of intersection types

Intersection types are especially useful when building complex systems in Jurassic Park:

1. Composing behaviors

// Defining different abilities
interface Swimming {
  swimmingSpeed: number; // km/h
  maxDepth: number;    // meters
  underwaterEndurance: number; // minutes
}

interface Flying {
  wingspan: number; // meters
  flightSpeed: number;       // km/h
  maxAltitude: number;       // meters
}

// A dinosaur that can both swim and fly (like Pteranodon)
type FlyingISwimmingDinosaur = BasicDinosaur & Flying & Swimming;

const pteranodon: FlyingISwimmingDinosaur = {
  id: 201,
  name: "Pterri",
  species: "Pteranodon",
  age: 12,

  // Flying abilities
  wingspan: 8,
  flightSpeed: 90,
  maxAltitude: 500,

  // Swimming abilities
  swimmingSpeed: 20,
  maxDepth: 10,
  underwaterEndurance: 3
};

2. Extending existing types

// Basic security interface for all enclosures
interface BasicSecuritySystem {
  doubleFence: boolean;
  videoMonitoring: boolean;
  motionSensors: boolean;
}

// Additional security measures for predators
interface PredatorSecurityMeasures {
  electricVoltage: number; // volts
  wallThickness: number; // cm
  securityDome: boolean;
}

// Full security system for predator enclosure
type PredatorEnclosure = BasicSecuritySystem & PredatorSecurityMeasures;

// Using intersection to add enclosure information
type TRexEnclosure = PredatorEnclosure & {
  area: number; // hectares
  terrainLayout: string[];
  realisticVegetation: boolean;
};

const rexEnclosure: TRexEnclosure = {
  // BasicSecuritySystem
  doubleFence: true,
  videoMonitoring: true,
  motionSensors: true,

  // PredatorSecurityMeasures
  electricVoltage: 10000,
  wallThickness: 50,
  securityDome: false,

  // Specific to TRexEnclosure
  area: 8,
  terrainLayout: ["tall grass", "hills", "stream"],
  realisticVegetation: true
};

3. Combining functionality in complex systems

// Observation system interface
interface ObservationSystem {
  cameras: number;
  resolution: string;
  infraredTracking: boolean;

  startRecording(): void;
  stopRecording(): void;
}

// Alarm system interface
interface AlarmSystem {
  soundSignal: boolean;
  lightSignal: boolean;
  smsNotification: boolean;

  triggerAlarm(level: number): void;
  disableAlarm(): void;
}

// Complex security system combining both functionalities
type ParkSecuritySystem = ObservationSystem & AlarmSystem;

// Implementation of the security system
class FullSecuritySystem implements ParkSecuritySystem {
  // ObservationSystem
  cameras: number = 24;
  resolution: string = "4K";
  infraredTracking: boolean = true;

  startRecording(): void {
    console.log("Starting recording from all cameras");
  }

  stopRecording(): void {
    console.log("Stopping recording");
  }

  // AlarmSystem
  soundSignal: boolean = true;
  lightSignal: boolean = true;
  smsNotification: boolean = true;

  triggerAlarm(level: number): void {
    console.log(`Activating level ${level} alarm!`);
    if (this.soundSignal) console.log("Sirens activated");
    if (this.lightSignal) console.log("Warning lights activated");
    if (this.smsNotification) console.log("Sending SMS notifications to staff");
  }

  disableAlarm(): void {
    console.log("Disabling all alarm systems");
  }

  // Additional methods specific to the full system
  initiateSecurityProcedure(threatCode: string): void {
    console.log(`Initiating security procedure: ${threatCode}`);
    this.startRecording();
    this.triggerAlarm(threatCode === "RED" ? 3 : 1);
  }
}

// Using the system
const securitySystem = new FullSecuritySystem();
securitySystem.initiateSecurityProcedure("RED");

Combining union and intersection - advanced cases

The true power of TypeScript is revealed when we combine union and intersection types into more complex structures - just as Dr. Wu combines DNA from different species to create entirely new dinosaurs.

// Basic dinosaur types
interface Dinosaur {
  id: number;
  name: string;
  species: string;
}

interface LandDinosaur {
  environment: "land";
  runSpeed: number; // km/h
}

interface WaterDinosaur {
  environment: "water";
  swimmingSpeed: number; // km/h
  maxDepth: number; // meters
}

interface AirDinosaur {
  environment: "air";
  flightSpeed: number; // km/h
  maxAltitude: number; // meters
}

// Types for different abilities
interface HuntingAbilities {
  biteForce: number; // PSI
  huntingStrategy: "ambush" | "chase" | "pack";
}

interface HerbivoreDefensiveAbilities {
  armor: boolean;
  horns: boolean;
  spikes: boolean;
  defensiveStrength: number; // 1-10
}

// Complex type using union and intersection
type ParkDinosaur = Dinosaur &
  (
    (LandDinosaur & HuntingAbilities) |
    (LandDinosaur & HerbivoreDefensiveAbilities) |
    (WaterDinosaur & HuntingAbilities) |
    (AirDinosaur & HuntingAbilities)
  );

// Examples of use
const tyrannosaurus: ParkDinosaur = {
  id: 1,
  name: "Rex",
  species: "Tyrannosaurus Rex",
  environment: "land",
  runSpeed: 30,
  biteForce: 12800,
  huntingStrategy: "chase"
};

const stegosaurus: ParkDinosaur = {
  id: 2,
  name: "Spike",
  species: "Stegosaurus",
  environment: "land",
  runSpeed: 7,
  armor: true,
  horns: false,
  spikes: true,
  defensiveStrength: 8
};

// Function handling complex types
function analyzeDinosaur(dino: ParkDinosaur): void {
  console.log(`Analyzing: ${dino.name} (${dino.species})`);

  // Check the environment
  if (dino.environment === "land") {
    console.log(`Running speed: ${dino.runSpeed} km/h`);

    // Check whether it's a predator or herbivore
    if ("biteForce" in dino) {
      console.log(`Predator - bite force: ${dino.biteForce} PSI`);
      console.log(`Hunting strategy: ${dino.huntingStrategy}`);
    } else if ("defensiveStrength" in dino) {
      console.log("Herbivore with defensive mechanisms:");
      if (dino.armor) console.log("- Has armor");
      if (dino.horns) console.log("- Has horns");
      if (dino.spikes) console.log("- Has spikes");
      console.log(`Defensive strength: ${dino.defensiveStrength}/10`);
    }
  } else if (dino.environment === "water") {
    console.log(`Aquatic predator - swimming speed: ${dino.swimmingSpeed} km/h`);
    console.log(`Maximum depth: ${dino.maxDepth} m`);
  } else if (dino.environment === "air") {
    console.log(`Aerial predator - flying speed: ${dino.flightSpeed} km/h`);
    console.log(`Maximum flight altitude: ${dino.maxAltitude} m`);
  }
}

analyzeDinosaur(tyrannosaurus);
console.log("---");
analyzeDinosaur(stegosaurus);

Summary

Union and intersection types are like Dr. Wu's advanced genetic engineering techniques - they give us extraordinary power and flexibility in designing complex TypeScript systems.

TypeOperatorJurassic Park analogyUse
Union``Enclosure that can hold different dinosaurs (but only one kind at a time)Variables that can have different types
Discriminated Union`` with discriminating propertyDinosaur identification system for different speciesSafe handling of different type variants
Intersection&Combining DNA from different dinosaursCombining interfaces/types into more complex structures

Dr. Wu summarizes today's lesson: "TypeScript, like our genetics laboratory, gives us enormous possibilities. Thanks to union and intersection types we can create systems precisely tailored to our needs, combining simple elements into complex structures. However remember - with great power comes great responsibility. Use this knowledge wisely to create a safe and reliable park."

Code for this lesson: index.ts
// Union and intersection types in Jurassic Park
console.log("Union and Intersection Types\n");

// ===========================================
// 1. UNION TYPES - type A or B
// ===========================================
console.log("=== UNION TYPES ===");

// A simple union type
type DinosaurDiet = "carnivore" | "herbivore" | "omnivore";

let trexDiet: DinosaurDiet = "carnivore";
let brachiosaurDiet: DinosaurDiet = "herbivore";

console.log("T-Rex diet:", trexDiet);
console.log("Brachiosaurus diet:", brachiosaurDiet);

// Union with different types
type ID = number | string;

let paddockId: ID = "P-01";
let dinosaurId: ID = 123;

console.log("Paddock ID:", paddockId);
console.log("Dinosaur ID:", dinosaurId);

// Union with objects
interface Carnivore {
  type: "carnivore";
  huntingStyle: string;
  preySize: string;
}

interface Herbivore {
  type: "herbivore";
  plantPreference: string;
  grazingHours: number;
}

type Dinosaur = Carnivore | Herbivore;

const trex: Carnivore = {
  type: "carnivore",
  huntingStyle: "ambush predator",
  preySize: "large"
};

const triceratops: Herbivore = {
  type: "herbivore",
  plantPreference: "ferns and cycads",
  grazingHours: 16
};

// Type guards for union types
function describeDiet(dino: Dinosaur): string {
  if (dino.type === "carnivore") {
    return `Carnivore: ${dino.huntingStyle}, preys on ${dino.preySize} animals`;
  } else {
    return `Herbivore: prefers ${dino.plantPreference}, grazes ${dino.grazingHours}h/day`;
  }
}

console.log("\nT-Rex:", describeDiet(trex));
console.log("Triceratops:", describeDiet(triceratops));

// ===========================================
// 2. INTERSECTION TYPES - type A and B
// ===========================================
console.log("\n=== INTERSECTION TYPES ===");

// Combining types
interface HasName {
  name: string;
}

interface HasWeight {
  weight: number;
}

interface HasDiet {
  diet: DinosaurDiet;
}

// Intersection - must have all properties
type CompleteDinosaur = HasName & HasWeight & HasDiet;

const velociraptor: CompleteDinosaur = {
  name: "Blue",
  weight: 350,
  diet: "carnivore"
};

console.log("Complete dinosaur:", velociraptor);

// Extending interfaces through intersection
interface BasicInfo {
  id: number;
  species: string;
}

interface LocationInfo {
  paddockId: string;
  zone: string;
}

interface HealthInfo {
  isHealthy: boolean;
  lastCheckup: Date;
}

type FullDinosaurInfo = BasicInfo & LocationInfo & HealthInfo;

const rexy: FullDinosaurInfo = {
  id: 1,
  species: "Tyrannosaurus Rex",
  paddockId: "P-01",
  zone: "Carnivore Zone",
  isHealthy: true,
  lastCheckup: new Date()
};

console.log("\nFull info:", rexy);

// ===========================================
// 3. Combining Union and Intersection
// ===========================================
console.log("\n=== UNION + INTERSECTION ===");

interface Swimmer {
  swimSpeed: number;
}

interface Runner {
  runSpeed: number;
}

interface Flyer {
  flySpeed: number;
}

// Dinosaur can swim OR fly, BUT must be able to run
type ActiveDinosaur = Runner & (Swimmer | Flyer);

const mosasaurus: ActiveDinosaur = {
  runSpeed: 5, // slow on land
  swimSpeed: 50 // fast in the water
};

const pteranodon: ActiveDinosaur = {
  runSpeed: 10,
  flySpeed: 80
};

console.log("Mosasaurus:", mosasaurus);
console.log("Pteranodon:", pteranodon);

// ===========================================
// 4. Practical uses
// ===========================================
console.log("\n=== PRACTICAL USES ===");

// API Response type
type SuccessResponse = {
  status: "success";
  data: any;
};

type ErrorResponse = {
  status: "error";
  message: string;
  code: number;
};

type ApiResponse = SuccessResponse | ErrorResponse;

function handleResponse(response: ApiResponse): void {
  if (response.status === "success") {
    console.log("Data received:", response.data);
  } else {
    console.log(`Error ${response.code}: ${response.message}`);
  }
}

const success: ApiResponse = {
  status: "success",
  data: { dinosaurs: [trex, triceratops] }
};

const error: ApiResponse = {
  status: "error",
  message: "Paddock breach detected",
  code: 503
};

handleResponse(success);
handleResponse(error);

// Event types
interface BaseEvent {
  timestamp: Date;
  source: string;
}

interface FeedingEvent extends BaseEvent {
  type: "feeding";
  dinosaurId: number;
  foodAmount: number;
}

interface EscapeEvent extends BaseEvent {
  type: "escape";
  dinosaurId: number;
  paddockId: string;
  severity: "low" | "high";
}

interface MaintenanceEvent extends BaseEvent {
  type: "maintenance";
  paddockId: string;
  duration: number;
}

type ParkEvent = FeedingEvent | EscapeEvent | MaintenanceEvent;

function logEvent(event: ParkEvent): void {
  console.log(`[${event.timestamp.toISOString()}] ${event.source}`);

  switch (event.type) {
    case "feeding":
      console.log(`  Feeding dinosaur #${event.dinosaurId}: ${event.foodAmount}kg`);
      break;
    case "escape":
      console.log(`  ESCAPE from paddock ${event.paddockId}! Severity: ${event.severity}`);
      break;
    case "maintenance":
      console.log(`  Maintenance on paddock ${event.paddockId}: ${event.duration}h`);
      break;
  }
}

const feedingEvent: FeedingEvent = {
  type: "feeding",
  timestamp: new Date(),
  source: "Automated System",
  dinosaurId: 1,
  foodAmount: 400
};

const escapeEvent: EscapeEvent = {
  type: "escape",
  timestamp: new Date(),
  source: "Security Alert",
  dinosaurId: 1,
  paddockId: "P-01",
  severity: "high"
};

console.log("\nEvent log:");
logEvent(feedingEvent);
logEvent(escapeEvent);

// ===========================================
// 5. Summary
// ===========================================
console.log("\n=== SUMMARY ===");
console.log("Union Types (|) - value can be one of the types");
console.log("Intersection Types (&) - value must satisfy all types");
console.log("Type Guards - checking the type at runtime");
console.log("Discriminated Unions - distinguishing by field");

console.log("\nUnion and Intersection Types mastered!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the type string | number mean in TypeScript?

  2. 2. What does the type A & B (intersection type) do?

Hands-on tasks in the game

  • Code editor

    Create a union type DietType = 'herbivore' | 'carnivore' | 'omnivore' and an intersection type AquaticDino = Dinosaur & SwimmingAbility.

  • Horizontal ordering

    Arrange the elements of a type alias:

  • Click in order

    Arrange the elements of a union type definition:

  • Vertical ordering

    Arrange the steps of narrowing a union type in TypeScript:

  1. QuestionUnion Types
  2. QuestionIntersection Types
  3. Coding taskPractice: Union and Intersection Types
  4. Put in orderType Alias Syntax
  5. Click in orderSorting: Union Type Definition
  6. Put in orderNarrowing a Union Type

Useful articles