Generics in TypeScript
Write reusable, type-safe functions and types using generic type parameters.
What you'll learn
- What generics are and why they are called type parameters
- How to write generic functions and interfaces
- Constraining generics with the extends keyword
- Using multiple type parameters in a single definition
Concept
The Problem Generics Solve
Imagine a function that returns the first element of an array. Without generics, you would type it as function first(arr: any[]): any — but then the return type is any, losing all type information. Generics solve this by letting you declare a type variable that represents the element type: function first<T>(arr: T[]): T. When called with number[], TypeScript infers T = number and the return type is number. The function is reusable and type-safe.
Generic Syntax
You declare type parameters in angle brackets: <T> for one, <T, U> for two. They can appear in parameter types, return types, and the function body. Generic interfaces work the same way: interface Box<T> { value: T; }. Generic classes are common for data structures like stacks and queues: class Stack<T> { push(item: T): void; }.
Constraining Generics
Sometimes a generic type needs to have certain properties. You constrain it with extends: <T extends { length: number }> means T must have a length property. This lets you access item.length inside the function. The keyof operator is often used in constraints: <K extends keyof T> ensures K is a valid key of type T.
Example
// Generic function — T is inferred from the argument.
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
// Generic interface — describes a container holding any type.
interface Box<T> {
value: T;
}
// Constrained generic — T must have a 'length' property.
function getLength<T extends { length: number }>(item: T): number {
return item.length;
}
// Generic with keyof constraint — K must be a key of T.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const nums = first([10, 20, 30]); // T inferred as number
const strs = first(["a", "b", "c"]); // T inferred as string
const box: Box<string> = { value: "hello" };
console.log(nums, strs, box.value);
console.log(getLength("hello"), getLength([1, 2, 3]));
console.log(getProperty({ name: "Alice", age: 30 }, "name"));
Generics (<T>) are type variables inferred from usage. They make functions reusable without losing type safety. Constraints (extends) limit what T can be and let you access its properties.
Try it
- JSON to TypeScript
Generic patterns like Box<T> and Response<T> are common in typed APIs.
- JSON Formatter
Format generic data structures to understand their shapes.
Common mistakes
The mistake
Using any instead of generics for reusable utility functions
The fix
Generics preserve type information through the function. Replace any with a type parameter <T> so the output type reflects the input type.
The mistake
Forgetting to constrain generics when accessing specific properties
The fix
If you access item.length inside a generic function, constrain T with <T extends { length: number }>. Without the constraint, the compiler cannot verify the property exists.
Practice Generics in TypeScript
10 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.