Course contentsShow
← TypeScript
Lesson 821 of 1,79619. Template Literal TypesFree lesson

Template Literals with Union Types

When unions are embedded in templates, TypeScript generates the cartesian product of all possible string combinations.

Template Literals with Union Types

You'll learn: How TypeScript generates all possible string combinations when unions appear in template literal types.

The Combinatorial Power of Unions in Templates

When you embed a union type inside a template literal type, TypeScript doesn't just preserve the union—it automatically generates every possible combination of strings by computing the cartesian product.

Think of it like a menu: if you have a union of "small" | "large" for sizes and "coffee" | "tea" for drinks, TypeScript creates all four combinations for you: "small-coffee", "small-tea", "large-coffee", "large-tea".

How It Works

type Size = "small" | "large";
type Drink = "coffee" | "tea";

// TypeScript generates all 4 combinations:
// "small-coffee" | "small-tea" | "large-coffee" | "large-tea"
type Order = `${Size}-${Drink}`;

The type system multiplies the possibilities: 2 sizes × 2 drinks = 4 total combinations.

Multiple Unions Multiply Quickly

type Prefix = "get" | "set";
type Property = "Name" | "Age";
type Suffix = "Sync" | "Async";

// Creates 2 × 2 × 2 = 8 combinations
type Method = `${Prefix}${Property}${Suffix}`;
// "getNameSync" | "getNameAsync" | "setNameSync" | etc.

Each union position multiplies the total count exponentially.

The Cartesian Product Explained

Just like in mathematics, TypeScript computes every pairing. If you have 3 colors and 4 sizes, you get 12 combinations. The order matters—${A}${B} differs from ${B}${A}.

This automatic expansion makes template literal types incredibly powerful for creating exhaustive string pattern types without manual enumeration.

Key Takeaway: Unions in template literals trigger automatic cartesian product expansion, generating all possible string combinations—but be mindful of exponential growth with multiple unions.