🔷 TypeScript Intermediate

What are generic default types in TypeScript?

Answer

Generic default types (TypeScript 2.3) allow you to specify a default type for a generic type parameter, similar to default parameter values in functions. Syntax: interface Container<T = string> { value: T; } — if T is not specified, it defaults to string. So Container is equivalent to Container<string>. Another example: function createArray<T = number>(length: number, fill: T): T[] { return Array(length).fill(fill); }. Defaults can reference earlier type parameters: type EventHandler<E extends Event = Event> = (event: E) => void;. Generic defaults are required to come after non-default type parameters. Use cases: library APIs where a sensible default exists but should be overridable (React's Component<P = {}, S = {}>), creating flexible yet convenient generic types. When you have multiple type parameters, trailing ones can have defaults even if leading ones do not.