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

const in Function Builders

Applying const type parameters to builder pattern functions that need to preserve exact literal types.

const in Function Builders

You'll learn: How to use const type parameters in builder pattern functions to preserve exact literal types throughout the build chain, ensuring maximum type safety and autocomplete accuracy.

The Builder Pattern Problem

Builder patterns let you construct objects step-by-step through method chaining. But without const type parameters, TypeScript widens literal types to their primitive counterparts, losing precision:

function createConfig<T>(initial: T) {
  return {
    value: initial,
    // Later builder methods would see widened types
  };
}

const config = createConfig({ mode: "development" });
// config.value.mode is typed as string, not "development"

Applying const to Builder Functions

By adding const before the type parameter, you tell TypeScript to infer the most specific literal type possible:

function createConfig<const T>(initial: T) {
  return {
    value: initial,
    extend<const U>(additional: U) {
      return createConfig({ ...initial, ...additional });
    }
  };
}

const config = createConfig({ mode: "development" });
// config.value.mode is now typed as "development" (literal!)

Why This Matters for Builders

Builder patterns often use configuration objects where exact values matter. When you chain .extend() or similar methods, you want subsequent calls to know exactly what values exist, not just that they're strings or numbers.

function query<const T>(table: T) {
  return {
    from: table,
    where<const U>(condition: U) {
      return { table, condition };
    }
  };
}

const result = query("users").where({ status: "active" });
// result.table is "users", result.condition.status is "active"

Think of It Like This

Imagine a form builder where you add fields one by one. Without const, it's like the builder forgets the specific field names and just remembers "some string." With const, it remembers "the username field" and "the email field" precisely, enabling perfect autocomplete for validation rules or access patterns.

Key Takeaway: Use const type parameters in builder functions when you need to preserve exact literal types through method chains, enabling type-safe APIs where configuration details matter at the type level.