Generic Defaults and API Design

Generic parameters can have defaults, which callers use when they do not provide an explicit type argument. Defaults should be sensible and should not hide uncertainty. For API response wrappers, a generic payload type is often useful; an error type can have a default if the library has a consistent convention.

Good generic APIs make common cases easy and unusual cases possible. Keep the number of type parameters small, order required parameters before defaulted ones, and avoid exposing internal type complexity when a simpler public contract would work.

A generic API response
type ApiResponse<TData, TError = string> =
  | { ok: true; data: TData }
  | { ok: false; error: TError };

const success: ApiResponse<{ id: string }> = {
  ok: true,
  data: { id: "u-1" }
};
💡 TData is inferred or supplied for each response. TError defaults to string, but callers can provide a structured error type when needed.
Key Takeaways
  • Generic defaults reduce repetitive type arguments.
  • Keep public generic APIs understandable.
  • Model success and failure as a discriminated union when their shapes differ.
Knowledge Check

When is a generic default used?