What is a default type parameter in a generic, and when is it useful?
A default like <T = string> is used when the caller gives no type argument and TypeScript cannot infer one. It keeps simple usage short while still allowing a custom type when needed.
Explain it simply
When you order tea at a tapri and say nothing, you get the usual: masala chai. You can still ask for ginger instead. A default type parameter works the same way.
Defaults matter most for generic types and interfaces, where there is no function call to infer from. They also make it possible to add a type parameter to an existing type without breaking old code, because old uses simply get the default.
Example
interface ApiResult<T = unknown> { ok: boolean; data: T; }
const raw: ApiResult = { ok: true, data: 123 }; // T defaults to unknown const users: ApiResult<string[]> = { ok: true, data: ["Asha", "Ravi"] };
// Default can refer to earlier parameters type Pair<A, B = A> = [A, B]; const p: Pair<number> = [1, 2]; // B defaults to number
function makeBox<T = string>(value?: T) { return { value }; } const box = makeBox(); // T is string
What to say in the interview
A default type parameter gives a fallback when nothing is specified or inferable. I use it on generic interfaces so that the common case needs no angle brackets, and to extend a type with a new parameter without breaking existing callers.
Common mistakes
- Expecting the default to override inference; if an argument lets TypeScript infer T, the default is ignored.