Trung BìnhTypeScript iconTypeScript

Generics trong TypeScript là gì? Tại sao cần thiết?

Generics cho phép tạo components (functions, classes, interfaces) hoạt động với nhiều kiểu dữ liệu mà vẫn type-safe.

Thay dùng any, dùng type parameter <T>.

typescript
// Không generic — mất type info
function identity(arg: any): any { return arg; }

// Generic — type-safe
function identity<T>(arg: T): T { return arg; }

const n = identity(42);    // n: number
const s = identity('hi');  // s: string

// Generic interface
interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

const res: ApiResponse<User[]> = await fetchUsers();

Tái sử dụng code mà không mất type information.

Xem toàn bộ TypeScript cùng filter theo level & chủ đề con.

Mở danh sách TypeScript