Level 11
Generics
Generics let you write functions, classes, and types that work over many types while preserving full type information, eliminating the need for any or repetitive overloads.
25 min read + quiz
Why Generics Exist
Imagine writing a function that returns the first element of an array. Without generics you have two bad options: write it once per element type (stringFirst, numberFirst, and so on), or type the parameter as any[] and throw away all type safety. Generics solve this by letting you declare a type parameter — a placeholder that gets filled in at each call site.
The key mental model is that a generic function is a function over types as well as values. When you call first([1, 2, 3]), TypeScript infers T to be number and the return type becomes number automatically. You wrote the logic once, but the compiler specializes the types for every caller.
A common beginner mistake is reaching for unknown or any when a generic would preserve information. If the output type depends on the input type in any way, that relationship is exactly what a type parameter expresses.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const n = first([10, 20, 30]); // n: number | undefined
const s = first(["a", "b"]); // s: string | undefined
const b = first([true, false]); // b: boolean | undefinedOne implementation, fully typed for every caller.
Generic Constraints with extends
Unconstrained type parameters can be anything, which means you can do almost nothing with them inside the function body — TypeScript only lets you use operations valid for every possible type. Constraints fix this: writing T extends HasLength tells the compiler that T will always have at least the members of HasLength.
Constraints are a contract in both directions. Callers must pass something assignable to the constraint, and in exchange the implementation may safely use those members. This is far better than casting, because the guarantee is checked at every call site.
A classic real-world use is constraining a key parameter with K extends keyof T. This is how lodash-style get functions and typed event emitters are built: the compiler proves the key exists on the object and infers the exact property type.
interface HasLength {
length: number;
}
function longest<T extends HasLength>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
longest("hello", "hi"); // OK: strings have length
longest([1, 2, 3], [4]); // OK: arrays have length
// longest(10, 20); // Error: number has no length
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const name = getProp(user, "name"); // name: stringConstraints unlock safe operations inside generic code.
Generic Interfaces and Classes
Type parameters are not limited to functions. Interfaces and classes can be generic too, which is how containers like Array<T>, Map<K, V>, and Promise<T> are defined in the standard library. When a class is generic, the parameter is fixed once per instance: a Stack<number> only ever holds numbers.
Generic interfaces shine when modeling API responses. Instead of defining UserResponse, ProductResponse, and OrderResponse separately, define one ApiResponse<T> wrapper and reuse it. This keeps the envelope (status, error fields) consistent across your whole codebase.
Note where you declare the parameter matters. Declaring it on the interface means the whole object commits to one type. Declaring it on a method means each call can pick its own type. Choose based on whether the type should be fixed per instance or per call.
interface ApiResponse<T> {
status: number;
data: T;
error?: string;
}
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
get size(): number {
return this.items.length;
}
}
const numbers = new Stack<number>();
numbers.push(1);
// numbers.push("two"); // Error: string not assignable to numberA generic class fixes T once per instance.
Default Type Parameters and Inference
Type parameters can have defaults, just like function parameters: interface Options<T = string> means callers who do not care get string for free. Defaults are especially useful in library code where the common case should require zero annotations.
In practice you should let inference do the work whenever possible. Explicitly writing first<number>([1, 2]) is redundant — the compiler already knows. Reserve explicit type arguments for cases where inference fails or where you want a wider type than the inferred one, such as useState<string | null>(null) in React.
One pitfall: a type parameter that appears only once in a signature is usually a design smell. If T appears only in the return type, the compiler has nothing to infer from and callers effectively get an unchecked cast. Make sure each parameter ties at least two positions together, or reconsider whether you need it.
interface PagedResult<T, TMeta = { page: number; total: number }> {
items: T[];
meta: TMeta;
}
// TMeta falls back to its default:
const result: PagedResult<string> = {
items: ["a", "b"],
meta: { page: 1, total: 2 },
};
// Suspicious: T appears only in the return position.
function parse<T>(json: string): T {
return JSON.parse(json); // effectively an unchecked cast!
}Defaults reduce noise; return-only type parameters hide casts.
Real-World Pattern: Typed Wrappers
Most day-to-day generic code is not exotic — it is thin, typed wrappers around untyped boundaries. A fetchJson<T> helper, a typed localStorage wrapper, or a memoize function all use one or two type parameters to thread type information from input to output.
When writing wrappers, prefer constraining at the boundary and keeping internals simple. It is fine for the implementation to use a few carefully-placed assertions as long as the public signature is honest. Users of your function only see the signature, so that is where correctness matters most.
Resist the urge to make everything generic. If a function genuinely only works with strings, declare it with string. Premature generics add reading cost without adding safety — add the type parameter when a second element type actually shows up.
async function fetchJson<T>(url: string): Promise<T> {
const res = await fetch(url);
if (!res.ok) {
throw new Error("HTTP " + res.status);
}
return res.json() as Promise<T>;
}
interface User {
id: number;
name: string;
}
// Call sites are fully typed:
// const user = await fetchJson<User>("/api/users/1");
// user.name is a string, user.id is a number.A typed wrapper: honest signature, small assertion inside.
Try it yourself
This lesson's example is preloaded in the playground — break it, fix it, extend it.
Open in playgroundCheck your understanding
Question 1 · Multiple choice
What is the main advantage of a generic function over one typed with any?
Question 2 · Predict the output
What does this program print?
function wrap<T>(value: T): { value: T } {
return { value };
}
const a = wrap("hi");
const b = wrap(5);
console.log(typeof a.value, typeof b.value);Question 3 · Find the error
This code fails to compile. Why?
function describe<T>(item: T): string {
return "Length is " + item.length;
}Question 4 · True or false
In getProp<T, K extends keyof T>(obj: T, key: K), the constraint guarantees at compile time that key is a real property of obj.
Question 5 · Multiple choice