BeCuriouzBeCuriouz

Learn something new every day

🔷 TypeScript
🎛️

Default Type Parameters: Sensible Fallbacks for Generics

💡 A default type parameter <T = X> makes a generic's type argument optional, falling back to X when none is provided or inferred.

Recall from earlier cards that a generic like lets a caller plug in a type. But what if most callers want the same type, and only a few need something special? That's where default type parameters come in — using the syntax , you give a type parameter a fallback that applies whenever the caller doesn't supply (and TypeScript can't infer) one.

ts
interface Container<T = string> {
  value: T;
}

const a: Container = { value: "hi" };        // T defaults to string
const b: Container<number> = { value: 42 };  // T explicitly number

Without the default, writing Container alone would be an error — TypeScript would demand a type argument. The = string makes the argument optional, so Container and Container mean exactly the same thing. This mirrors how default values work for function parameters (function f(x = 5)), but at the type level.

Two rules matter. First, just like default function parameters, defaulted type parameters must come after non-defaulted ones: is legal, is not. Second, a default can reference an earlier parameter — — which is handy when one type usually matches another. Defaults keep your generics flexible for power users while staying frictionless for the common case.

🎛️ Default Type Parameters: Sensible Fallbacks for Generics — BeCuriouz