Course contentsShow
← TypeScript
Lesson 1420 of 1,79632. Advanced PatternsFree lesson

Combining const with Constraints

How to use const alongside extends constraints to narrow within a bounded type space.

Combining const with Constraints

What you'll learn: How to use const type parameters together with extends constraints to preserve literal types while enforcing structural requirements.


When you need both precision (keeping exact literal values) and safety (ensuring values meet certain requirements), you can combine const type parameters with extends constraints.

The Core Idea

Think of const as a magnifying glass that preserves fine details, while extends acts as a quality checkpoint. Together, they let you say: "Keep all the specific details of what the user provides, but only if it matches this required shape."

Without constraints, a const parameter accepts anything and preserves it literally. With constraints, you narrow the acceptable inputs while still maintaining literal precision.

Basic Pattern

function processConfig<const T extends { mode: string }>(config: T) {
  return config;
}

const result = processConfig({ mode: "strict", timeout: 5000 });
// Type: { readonly mode: "strict"; readonly timeout: 5000 }
//       ↑ Exact literals preserved, AND structure validated

The extends { mode: string } ensures the object has a mode property, while const locks in "strict" as the literal type rather than widening to string.

Constraining Arrays While Preserving Elements

function createMenu<const T extends string[]>(items: T) {
  return items;
}

const menu = createMenu(["home", "about", "contact"]);
// Type: readonly ["home", "about", "contact"]
//       ↑ Tuple of literals, AND guaranteed to be string array

Union Type Constraints

type ValidStatus = "pending" | "active" | "complete";

function trackStatus<const T extends ValidStatus[]>(statuses: T) {
  return statuses;
}

const flow = trackStatus(["pending", "active"]);
// Type: readonly ["pending", "active"]

// Error: Type '"invalid"' is not assignable to type 'ValidStatus'
// const bad = trackStatus(["pending", "invalid"]);

Here you constrain to a specific union while still preserving the exact order and values as a tuple.

When This Pattern Shines

This combination is powerful for configuration objects, route definitions, or any API where you want to enforce a contract while extracting precise types for type-safe operations downstream.

Key Takeaway: Combining const with extends constraints gives you the best of both worlds—structural validation at the boundary and full literal precision for type inference, creating a bounded but highly specific type space.