Các utility type có sẵn
TypeScript có sẵn một bộ utility type — được viết bằng chính mapped type và conditional type bạn vừa học. Thuộc chúng giúp bạn không phải tự chế lại bánh xe.
Biến đổi thuộc tính object
interface User {
id: number;
name: string;
email: string;
avatar?: string;
}type UserPatch = Partial<User>; // mọi thuộc tính thành tùy chọn
type FullUser = Required<User>; // avatar thành bắt buộc
type FrozenUser = Readonly<User>; // mọi thuộc tính readonly
type UserPreview = Pick<User, "id" | "name">; // { id; name }
type NewUser = Omit<User, "id">; // bỏ id (server tự sinh)
type RolePerms = Record<"admin" | "member", string[]>;Ví dụ thực tế — hàm cập nhật nhận một phần dữ liệu:
function updateUser(id: number, patch: Partial<Omit<User, "id">>): User {
/* ... */
}
updateUser(1, { name: "Bình" }); // ✅
updateUser(1, { id: 2 }); // ❌ không được đổi idWARNING
Omit<T, K> không kiểm tra K có thuộc T hay không: Omit<User, "idd"> (gõ sai) vẫn hợp lệ và chẳng bỏ gì. Pick thì kiểm tra. Cẩn thận lỗi chính tả.
Lọc union
type Status = "draft" | "published" | "archived" | null;
type Active = Exclude<Status, "archived" | null>; // "draft" | "published"
type OnlyNull = Extract<Status, null>; // null
type NotNull = NonNullable<Status>; // "draft" | "published" | "archived"
type Shape =
| { kind: "circle"; r: number }
| { kind: "square"; size: number };
type Circle = Extract<Shape, { kind: "circle" }>; // lấy một nhánh của discriminated unionLàm việc với hàm và class
function createOrder(customerId: string, items: string[], note?: string) {
return { id: crypto.randomUUID(), customerId, items, note };
}
type Order = ReturnType<typeof createOrder>;
// { id: `${string}-${string}-...`; customerId: string; items: string[]; note: string | undefined }
type CreateOrderArgs = Parameters<typeof createOrder>;
// [customerId: string, items: string[], note?: string]
class ApiClient { constructor(public baseUrl: string) {} }
type ClientArgs = ConstructorParameters<typeof ApiClient>; // [baseUrl: string]
type Client = InstanceType<typeof ApiClient>; // ApiClientReturnType<typeof fn> rất hữu ích khi thư viện không export kiểu kết quả: bạn vẫn lấy được nó từ hàm.
Promise và suy luận
async function loadUser() { return { id: 1, name: "An" }; }
type LoadResult = ReturnType<typeof loadUser>; // Promise<{ id; name }>
type LoadedUser = Awaited<ReturnType<typeof loadUser>>; // { id; name }
type Deep = Awaited<Promise<Promise<number>>>; // numberNoInfer<T> (TS 5.4) cũng là một utility type: chặn suy luận từ một vị trí (xem lại chương Generics).
Bảng tra nhanh
| Utility | Kết quả |
|---|---|
Partial<T> / Required<T> | thêm / bỏ ? cho mọi thuộc tính |
Readonly<T> | thêm readonly |
Pick<T, K> / Omit<T, K> | giữ / bỏ một số khóa |
Record<K, V> | object khóa K, giá trị V |
Exclude<U, X> / Extract<U, X> | bỏ / giữ thành viên union gán được cho X |
NonNullable<T> | bỏ null và undefined |
ReturnType<F> / Parameters<F> | kiểu trả về / tuple tham số |
ConstructorParameters<C> / InstanceType<C> | tham số constructor / kiểu instance |
Awaited<T> | "mở" Promise lồng nhau |
NoInfer<T> | không suy luận từ vị trí này |
Uppercase, Capitalize… | biến đổi kiểu chuỗi |
TIP
Dùng Pick/Omit để suy ra kiểu từ một nguồn duy nhất (model chính), thay vì viết lại các interface gần giống nhau. Khi model đổi, mọi kiểu suy ra tự cập nhật.
Comments