Advertisement
Intermediate TypeScript, Generics

How do you provide a default type for a generic parameter, similar to a default function parameter?

Short answer

Write ` ` after the type parameter name; if the caller doesn't explicitly specify T and it can't be inferred from context, the default type is used instead, similar in spirit to default function parameter values.

Save TypeScript mock interview
Advertisement
AModel answer
Write `<T = DefaultType>` after the type parameter name; if the caller doesn't explicitly specify T and it can't be inferred from context, the default type is used instead, similar in spirit to default function parameter values.
interface ApiResponse<T = unknown> {
  data: T;
  status: number;
}
const response: ApiResponse = { data: 'anything', status: 200 }; // T defaults to unknown
Real-world example
Providing a sensible fallback generic type for a widely-used utility type or interface when callers don't always need to specify it.
Likely follow-ups
  • Can a later generic type parameter's default reference an earlier type parameter in the same declaration?
Related topics