EasyGenerics📖 Theory Question

What are default type parameters in TypeScript generics?

💡

Hint

Like default function parameters — a fallback type when the type argument is not specified

Full Answer

Default type parameters provide a fallback type when the caller doesn't explicitly provide one.

// Without default — must always specify T
interface Event<T> {
  type: string;
  payload: T;
}

// With default — T falls back to unknown when not specified
interface Event<T = unknown> {
  type: string;
  payload: T;
}

const genericEvent: Event = { type: 'click', payload: { x: 10 } };
// T inferred as unknown — must narrow payload before using

const typedEvent: Event<MouseData> = { type: 'click', payload: mouseData };
// T is MouseData — payload is fully typed

Practical use cases:

// Promise default is unknown in strict mode, any otherwise
// Custom Result type with default error type
type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };

function fetchUser(): Promise<Result<User>> {
  // Result<User, Error> — E defaults to Error
}

// Component props with optional extension
interface TableProps<T = Record<string, unknown>> {
  data: T[];
  columns: Array<keyof T>;
}

const table: TableProps = { data: [{}], columns: [] };
// T defaults to Record<string, unknown>
💡 Defaults must come after non-default type parameters, just like JavaScript default arguments. <T, E = Error> is valid; <T = Error, E> is not.

More Generics Questions

EasyWhat are generics and why are they useful in TypeScript?EasyWhat are generic constraints and how do you use the extends keyword with them?EasyWhat is conditional generic typing — how do you write T extends U ? X : Y?MediumHow do generic functions differ from generic types? Show examples of each.

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint