T = Default Generic Parameter Defaults
Last updated: 2026-10-22
T = Default Generic Parameter Defaults
Type parameters can have defaults (<T = string>): omitted means the default applies, specified means your choice wins. Same idea as default function parameters — zero config for common cases, override for special ones — making generic APIs friendlier.
| Group | Generics |
|---|---|
| Kind | Syntax |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
interface Paginated<T = string, Page = number> {
page: Page;
items: T[];
}
const names: Paginated = { page: 1, items: ["ann", "bob"] }; // defaults
const orders: Paginated<{ id: number; total: number }> = { page: 2, items: [] }; // override T
⚙️ Parameters
| T = string | A defaulted type parameter: can be omitted entirely at the use site |
|---|---|
| Page = number | The second parameter defaults too: overriding Page requires writing T first (positional filling) |
Returns:Defaults only decide which type applies when omitted; an instantiated type behaves identically to an explicitly specified one.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
ann,bob 2 7
(Runtime output after transpilation; pushing a string into orders.items is a compile error — T was overridden to the order object)
💡 Notes
ℹ️ Info A default can be any type expression: a concrete type (string), another parameter (T = Page[]), even a conditional type — defaults are full type-level computation.
⚠️ Note Parameters fill positionally: to override the second (Page), the first (T) must be written too (its default or a placeholder).
💡 Tip Library generics should almost always have defaults (e.g. Paginated<T = unknown>): beginners get going without understanding the parameter, advanced users specify precisely.
🏷️ Related Generics
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q Any rules for defaults plus constraints?
A The default must satisfy the constraint: <T extends HasId = User> is legal (User fits HasId), <T extends HasId = string> errors. Defaults are fallback types; constraints are the gate.
Q When does a generic class's default kick in?
A For new Stack() with no arguments and nothing to infer: class Stack<T = string> gives Stack<string>. Constructor arguments take precedence over the default via inference.
Q Can a default reference earlier type parameters?
A Yes: interface Pair<K = string, V = K[]> — V defaults to an array of K. References point forward to already-declared parameters only.