← Quay lại blog
·1 min read

Utility Types Trong TypeScript Bạn Nên Biết

TypeScript cung cấp nhiều utility types giúp transform types một cách linh hoạt.

Partial và Required

interface User {
  name: string;
  email: string;
  age: number;
}
 
// Tất cả fields trở thành optional
type UpdateUser = Partial<User>;
 
// Tất cả fields trở thành required
type StrictUser = Required<User>;

Pick và Omit

// Chỉ lấy name và email
type UserPreview = Pick<User, 'name' | 'email'>;
 
// Bỏ age
type UserWithoutAge = Omit<User, 'age'>;

Record

type Role = 'admin' | 'user' | 'guest';
 
const permissions: Record<Role, string[]> = {
  admin: ['read', 'write', 'delete'],
  user: ['read', 'write'],
  guest: ['read'],
};

Extract và Exclude

type Status = 'active' | 'inactive' | 'pending' | 'deleted';
 
// Chỉ lấy active statuses
type ActiveStatus = Extract<Status, 'active' | 'pending'>;
// Result: 'active' | 'pending'
 
// Loại bỏ deleted
type VisibleStatus = Exclude<Status, 'deleted'>;
// Result: 'active' | 'inactive' | 'pending'

ReturnType và Parameters

function createUser(name: string, age: number) {
  return { id: Math.random(), name, age };
}
 
type UserReturn = ReturnType<typeof createUser>;
// { id: number; name: string; age: number }
 
type UserParams = Parameters<typeof createUser>;
// [name: string, age: number]

Awaited

type Response = Promise<{ data: User[] }>;
type Data = Awaited<Response>;
// { data: User[] }

Custom Utility Type

// DeepPartial — recursive Partial
type DeepPartial<T> = {
  [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};

Nắm vững utility types giúp code TypeScript clean và type-safe hơn rất nhiều.

Nhận bài viết mới

Bài viết mới gửi thẳng vào inbox. Không spam, unsubscribe bất cứ lúc nào.