Skip to content
typescript questions

TypeScript · 2 of 10middle~1 min

What are generics and why are they useful?

#generics#core

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: number

Generic constraints

ts
function getLength<T extends { length: number }>(value: T): number { return value.length; } getLength('hello'); // 5 getLength([1, 2, 3]); // 3

Generic 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?

read more on the blog

view all

related questions