Generics allow you to write reusable, type-safe code that works with multiple types. Instead of using any, generics preserve type information while keeping your code flexible.
TypeScript
Beginner
12 min read
Generics in TypeScript
Example
// Generic function
function identity<T>(value: T): T {
return value;
}
identity<string>('hello'); // returns string
identity<number>(42); // returns number
// Generic interface
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
interface User { id: number; name: string; }
const response: ApiResponse<User[]> = {
data: [{ id: 1, name: 'Alice' }],
status: 200,
message: 'OK',
};
// Generic class
class Stack<T> {
private items: T[] = [];
push(item: T): void { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
peek(): T | undefined { return this.items[this.items.length - 1]; }
get size(): number { return this.items.length; }
}
const numStack = new Stack<number>();
numStack.push(1);
numStack.push(2);
console.log(numStack.pop()); // 2
// Constrained generic
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript