0Pricing
TypeScript Academy · Lesson

Practical Patterns with Union and Intersection

Apply unions and intersections in real-world scenarios.

Practical Patterns with Union and Intersection is a free TypeScript Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome

Union and intersection types power many real-world TypeScript patterns. This lesson explores practical combinations you'll use in production code.

Optional Payload Pattern

Model functions or events that may or may not carry data with a union.
type Event =
  | { type: 'click'; x: number; y: number }
  | { type: 'keypress'; key: string }
  | { type: 'blur' };

Builder/Mixin with Intersection

Use intersections to compose feature sets into a combined type.
type Serializable = { serialize(): string };
type Validatable = { validate(): boolean };
type Model = Serializable & Validatable & { id: number };

Union for Input Normalization

Accept flexible input types in a function and normalize them to a canonical type.
function toArray<T>(val: T | T[]): T[] {
  return Array.isArray(val) ? val : [val];
}

Branded Types with Intersection

Create distinct types from the same primitive using intersections with a unique brand marker.
type UserId = number & { __brand: 'UserId' };
type PostId = number & { __brand: 'PostId' };
// Prevents accidentally mixing IDs

WithOptional Pattern

Use intersection with Partial to create a base type where some fields are required and others optional.
type RequiredFields = { id: number; email: string };
type OptionalFields = Partial<{ name: string; bio: string }>;
type UserUpdate = RequiredFields & OptionalFields;

Polymorphic Component Props

In React, union types allow component props to vary based on a discriminant.
type ButtonProps =
  | { variant: 'primary'; onClick: () => void }
  | { variant: 'link'; href: string };

Extending Third-Party Types

Intersect third-party types with your own additions.
import type { Request } from 'express';
type AuthRequest = Request & { user: User };

Combining Union and Intersection

Union and intersection can be combined. Parentheses control precedence.
type Admin = { role: 'admin' };
type User = { role: 'user' };
type LoggedIn = { sessionId: string };
type AuthUser = (Admin | User) & LoggedIn;

Type Guards for Union Members

Write a reusable type guard function to narrow a union without repeating checks.
function isAdmin(u: AuthUser): u is Admin & LoggedIn {
  return u.role === 'admin';
}

Distributive Behavior in Intersections

Distributive law: A & (B | C) = (A & B) | (A & C). TypeScript applies this automatically.
type Base = { id: number };
type AB = Base & (string | number);
// equivalent to: (Base & string) | (Base & number)

Quick Check

Which pattern creates a distinct type from `number` to prevent accidental mixing of IDs?

Recap

Union and intersection types combine to model complex real-world shapes: branded IDs, mixin behaviors, flexible inputs, and discriminated component props. Master these patterns for production-grade TypeScript.

Frequently asked questions

Is the “Practical Patterns with Union and Intersection” lesson free?

Yes — the full text of “Practical Patterns with Union and Intersection” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Practical Patterns with Union and Intersection”?

Apply unions and intersections in real-world scenarios. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Practical Patterns with Union and Intersection” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Union Types: A or B
  2. Intersection Types: A and B
  3. Discriminated Unions for Safe Pattern Matching
  4. Practical Patterns with Union and Intersection
← Back to TypeScript Academy