
Alex Kim
Đăng ngày 13 tháng 11, 2025

Thành thạo Partial, Pick, Omit, Record, Exclude, Extract, ReturnType và nhiều hơn — với mẫu thực tế và best practices.
Bạn không cần viết mọi type từ đầu.
TypeScript đi kèm utility types tích hợp — như Partial<T>, Pick<T, K>, Record<K, T>, và cả union manipulators như Exclude<T, U>.
Chúng biến đổi, lọc và kết hợp types với độ chính xác phẫu thuật.
Hãy cùng đi sâu. Với ví dụ thực tế bạn sẽ dùng mỗi ngày.
| Utility | Chức năng | Use Case |
|---|---|---|
| Partial<T> | Làm tất cả properties optional | Cập nhật form, patch APIs |
| Required<T> | Làm tất cả properties required | Xác thực config |
| Pick<T, K> | Chọn keys cụ thể | DTOs, props subsets |
| Omit<T, K> | Loại bỏ keys cụ thể | Ẩn trường nội bộ |
| Record<K, T> | Map keys sang type | Dictionaries, lookups |
Partial<T>: Cập nhật Không Cần Đầy Đủ Objectinterface User { id: string; name: string; email: string; role: 'admin' | 'user';}function updateUser(id: string, changes: Partial<User>) {// Chỉ cập nhật các trường được cung cấp}Required<T>: Bắt buộc Tất Cả Trườnginterface Config { apiUrl?: string; timeout?: number;}const appConfig: Required<Config> = { apiUrl: 'https://api.example.com', timeout: 5000,};Pick<T, K>: Trích Xuất Những Gì Bạn Cầninterface User { id: string; name: string; email: string; password: string;}type PublicUser = Pick<User, 'id' | 'name' | 'email'>;Omit<T, K>: Loại Bỏ Những Gì Không Muốntype UserWithoutPassword = Omit<User, 'password'>;// → { id: string; name: string; email: string; }Record<K, T>: Dictionaries An Toàn Kiểuconst statusLabels: Record<'pending' | 'success' | 'error', string> = { pending: 'Đang xử lý', success: 'Thành công', error: 'Lỗi',};Những utility này làm việc với unions, functions và classes.
| Utility | Chức năng | Use Case |
|---|---|---|
| Exclude<T, U> | Loại U khỏi union T | Lọc event types |
| Extract<T, U> | Giữ chỉ types assignable cho U | Trích xuất string literals |
| NonNullable<T> | Loại bỏ null và undefined | API responses |
| ReturnType<T> | Lấy return type của function | Type-safe factories |
| Parameters<T> | Lấy parameter tuple của function | HOC, mocks |
| InstanceType<T> | Lấy instance type của class | DI, services |
Exclude<T, U>: Lọc Bỏ Typestype Event = 'click' | 'hover' | 'scroll' | 'keydown';type MouseEvent = Exclude<Event, 'keydown'>;// → 'click' | 'hover' | 'scroll'Extract<T, U>: Giữ Types Khớptype Primitive = string | number | boolean | null;type Truthy = Extract<Primitive, boolean | number | string>;// → string | number | booleanNonNullable<T>: Loại bỏ null/undefinedtype ApiResponse = User | null;function processUser(user: NonNullable<ApiResponse>) {// user được đảm bảo là User}ReturnType<T>: Lấy Kiểu Trả Về Hàmfunction getUser() { return { id: '1', name: 'Alex' };}type UserResult = ReturnType<typeof getUser>;// → { id: string; name: string; }Parameters<T>: Lấy Tham Số Hàmfunction apiCall(url: string, method: 'GET' | 'POST') { }type ApiParams = Parameters<typeof apiCall>;// → [url: string, method: 'GET' | 'POST']InstanceType<T>: Kiểu Instance của Classclass UserService { getUser() { return { name: 'Alex' }; }}type Service = InstanceType<typeof UserService>;// → UserServicetype UserPatch = Partial<Pick<User, 'name' | 'email'>> & { id: string };type Handler = (req: Request) => Promise<Response>;type HandlerParams = Parameters<Handler>;// 1. Duplicate thủ cônginterface UserDTO { id: string; name: string; email: string; }// 2. any cho mapsconst cache: any = {};// 3. Sai Excludetype Bad = Exclude<string | number, string | boolean>;// 1. Tái sử dụng với Pick/Omittype UserDTO = Pick<User, 'id' | 'name' | 'email'>;// 2. Record cho lookupsconst routes: Record<string, () => void> = {};// 3. Kết hợp cho types phức tạptype UpdatePayload = { id: string } & Partial<User>;Partial<T> → props optionalRequired<T> → tất cả requiredPick<T, K> → chọn keysOmit<T, K> → loại bỏ keysRecord<K, T> → typed mapExclude<T, U> → loại khỏi unionExtract<T, U> → giữ trong unionNonNullable<T> → loại null/undefinedReturnType<T> → lấy kiểu trả vềParameters<T> → lấy tham số hàmInstanceType<T> → kiểu instance classConstructorParameters<T> → tham số constructorUtility types không phải shortcuts — chúng là đòn bẩy.
Bạn không chỉ tiết kiệm dòng code. Bạn đang loại trừ bugs, thực thi contracts và mở rộng type safety.
Từ Partial<Pick<T, K>> đến ReturnType<typeof fn>,
mỗi utility là một pattern được chưng cất thành một từ duy nhất.
Hãy thành thạo chúng. Types của bạn sẽ cảm ơn bạn.
Viết bởi Alex Kim
#TypeScript #UtilityTypes #AdvancedTS #TypeSafety #Exclude #Extract #ReturnType #Pick #Omit #Record #WebDev