Multiple Generics & Defaults
Using multiple type variables and setting default fallback types.
More than one T
A generic signature isn't limited to a single <T>. You can declare as many generic variables as you need by separating them with commas: <T, U, V>.
Just like function parameters can have default values (function fn(x = 10)), generic variables can have default types (<T = string>).
Mapping and Fallbacks
Multiple generics are required when an operation transforms one type into a completely different type (like mapping an array of strings into an array of numbers).
Default generics are useful for building flexible libraries where a type is optional, providing a fallback so the user doesn't have to constantly type <string>.
Syntax
typescript
// 1. Multiple Generics
function tuple<T, U>(first: T, second: U): [T, U] {
return [first, second];
}
const pair = tuple("Alice", 42); // [string, number]
// 2. Default Generics
// If the caller doesn't provide a type, T defaults to Error.
interface Result<T = Error> {
success: boolean;
payload?: T;
}
// payload is Error
const res1: Result = { success: false, payload: new Error() };
// payload is string
const res2: Result<string> = { success: true, payload: "Done" };
Try it
Toggle whether the caller explicitly provides a type argument to see how the default generic fallback T = string engages.
Compile Success
UserstringBecause the caller omitted the second generic argument, U falls back to its default string type.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Separate multiple generic parameters with commas:
<T, U>. - Use
=to assign a default fallback type:<T = string>. - Default generics make passing type arguments optional for the caller.
- If you manually provide one generic argument to a function, you must provide all of them (that don't have defaults).
Done with this concept?
Mark it complete to track your progress. No login needed.