Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A default type parameter in TypeScript allows a generic type, interface, class, or function to specify a fallback type for a generic parameter. If the consumer of the generic does not explicitly provide a type argument and the compiler cannot infer one from the context, TypeScript automatically assigns the default type.

Syntax

The default type is assigned using the = operator within the generic angle brackets < >.
<T = DefaultType>
<T extends ConstraintType = DefaultType>

Rules and Mechanics

When defining default type parameters, the TypeScript compiler enforces strict structural rules: 1. Ordering and Cascading Defaults Required type parameters must strictly precede optional (defaulted) type parameters. Once a default type is declared for a parameter, all subsequent type parameters in the generic list must also be initialized with a default type.
// Valid: Required parameter 'T' precedes defaulted parameter 'U'
type Pair<T, U = boolean> = { first: T, second: U };

// Invalid: Required parameter 'U' follows defaulted parameter 'T'
// Error: Required type parameters may not follow optional type parameters.
type InvalidPair<T = string, U> = { first: T, second: U }; 
2. Constraint Satisfaction If a type parameter is bounded by a constraint using the extends keyword, the default type must strictly satisfy that constraint.
// Valid: 'string' satisfies the 'string | number' constraint
type Identifier<T extends string | number = string> = { id: T };

// Invalid: 'boolean' does not satisfy the 'string | number' constraint
// Error: Type 'boolean' does not satisfy the constraint 'string | number'.
type InvalidIdentifier<T extends string | number = boolean> = { id: T }; 
3. Forward Referencing A default type parameter can reference preceding type parameters declared within the same generic list. It cannot reference type parameters declared after it.
// Valid: 'U' defaults to whatever type is resolved for 'T'
type Transformer<T, U = T> = {
    input: T;
    output: U;
};

let identity: Transformer<number>; // T = number, U = number
let cast: Transformer<number, string>; // T = number, U = string

Resolution Order

When the TypeScript compiler processes a generic invocation, it resolves the type parameter in the following order:
  1. Explicit Assignment: The type explicitly passed in the angle brackets (e.g., Container<number>).
  2. Inference: The type inferred from the function arguments or assignment context.
  3. Default Type: The fallback type defined by the = operator in the generic declaration.
  4. Constraint Fallback: If no default exists and inference fails, it falls back to the constraint type (if extends is used) or unknown/{}.
Master TypeScript with Deep Grasping Methodology!Learn More