Generics
Generics allow you to write reusable, type-safe code that works with different types without losing type information.
Without generics
ts
// loses type information
function identity(value: any): any {
return value;
}With generics
ts
function identity<T>(value: T): T {
return value;
}
const str = identity('hello'); // type: string
const num = identity(42); // type: numberGeneric constraints
ts
function getLength<T extends { length: number }>(value: T): number {
return value.length;
}
getLength('hello'); // 5
getLength([1, 2, 3]); // 3Generic interfaces and types
ts
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
type UserResponse = ApiResponse<User>;
type ListResponse = ApiResponse<User[]>;Generics are the foundation of reusable utilities like
Array<T>,Promise<T>,Record<K, V>- they are everywhere in TypeScript.
updated
did you know it?