Pattern type-safe: builder, state machine, bảng tra đầy đủ
Bạn đã có đủ "nguyên liệu": union, generic, mapped type, as const, satisfies. Bài này ghép chúng thành những pattern dùng hằng ngày, mỗi pattern biến một loại bug runtime thành lỗi compile.
1. Bảng tra đầy đủ với satisfies Record
Mỗi khi thêm một giá trị vào union, mọi bảng tra liên quan phải được cập nhật. Để compiler nhắc bạn:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"
const roleLabel = {
admin: "Quản trị",
editor: "Biên tập",
viewer: "Người xem",
} satisfies Record<Role, string>;Thêm "guest" vào ROLES → roleLabel báo lỗi thiếu khóa ngay. Mảng ROLES vẫn dùng được lúc chạy (render dropdown, kiểm tra input), còn kiểu Role được suy ra từ nó — một nguồn sự thật duy nhất.
2. switch đầy đủ với assertNever
type State =
| { status: "idle" }
| { status: "loading"; startedAt: number }
| { status: "success"; data: string[] }
| { status: "error"; error: string };
function assertNever(x: never): never {
throw new Error(`Chưa xử lý: ${JSON.stringify(x)}`);
}
function render(s: State): string {
switch (s.status) {
case "idle": return "Chưa tải";
case "loading": return "Đang tải...";
case "success": return s.data.join(", ");
case "error": return s.error;
default: return assertNever(s);
}
}So với s satisfies never, assertNever còn ném lỗi lúc chạy nếu dữ liệu từ API mang một status lạ — vừa kiểm tra compile, vừa phòng thủ runtime.
TIP
Union kiểu State ở trên tốt hơn hẳn { loading: boolean; error?: string; data?: string[] }: không thể tồn tại trạng thái vô lý như "đang tải nhưng đã có lỗi". Hãy làm cho trạng thái sai không biểu diễn được (make illegal states unrepresentable).
3. State machine: chỉ cho phép chuyển trạng thái hợp lệ
type OrderStatus = "draft" | "pending" | "paid" | "shipped" | "cancelled";
const transitions = {
draft: ["pending", "cancelled"],
pending: ["paid", "cancelled"],
paid: ["shipped", "cancelled"],
shipped: [],
cancelled: [],
} as const satisfies Record<OrderStatus, readonly OrderStatus[]>;
type NextOf<S extends OrderStatus> = (typeof transitions)[S][number];
function canMove<S extends OrderStatus>(from: S, to: NextOf<S>): boolean {
return (transitions[from] as readonly OrderStatus[]).includes(to);
}
canMove("draft", "pending"); // ✅
canMove("draft", "shipped"); // ❌ "shipped" không thuộc "pending" | "cancelled"
canMove("shipped", "draft"); // ❌ NextOf<"shipped"> là neverBảng transitions vừa là dữ liệu runtime, vừa sinh ra kiểu NextOf. Bài tập cuối chương sẽ cài đặt một máy trạng thái generic hoàn chỉnh.
4. Event emitter có kiểu
type AppEvents = {
login: { userId: string };
logout: undefined;
"cart:add": { sku: string; qty: number };
};
class Emitter<E extends Record<string, unknown>> {
#handlers: { [K in keyof E]?: Array<(payload: E[K]) => void> } = {};
on<K extends keyof E>(event: K, handler: (payload: E[K]) => void): void {
(this.#handlers[event] ??= []).push(handler);
}
emit<K extends keyof E>(event: K, payload: E[K]): void {
for (const h of this.#handlers[event] ?? []) h(payload);
}
}
const bus = new Emitter<AppEvents>();
bus.on("cart:add", (p) => console.log(p.sku, p.qty)); // p: { sku; qty }
bus.emit("login", { id: "u_1" }); // ❌ thiếu userId
bus.emit("signup", {}); // ❌ không có sự kiện "signup"Một "bản đồ sự kiện" (AppEvents) quyết định cả tên sự kiện lẫn kiểu payload — không còn gõ nhầm tên chuỗi.
5. Builder bắt buộc đủ trường
Generic có thể "ghi nhớ" những gì đã được thiết lập:
type Config = { url: string; method: "GET" | "POST"; timeoutMs: number };
class RequestBuilder<Done extends keyof Config = never> {
readonly #config: Partial<Config>;
constructor(config: Partial<Config> = {}) {
this.#config = config;
}
with<K extends keyof Config>(key: K, value: Config[K]): RequestBuilder<Done | K> {
return new RequestBuilder<Done | K>({ ...this.#config, [key]: value });
}
build(...missing: [Exclude<keyof Config, Done>] extends [never] ? [] : [missing: Exclude<keyof Config, Done>]): Config {
return this.#config as Config;
}
}
new RequestBuilder().with("url", "/orders").with("method", "GET").with("timeoutMs", 5000).build(); // ✅
new RequestBuilder().with("url", "/orders").with("method", "GET").build();
// ❌ Expected 1 arguments — rê chuột sẽ thấy tham số `missing: "timeoutMs"`WARNING
Pattern này mạnh nhưng làm thông báo lỗi khó đọc. Với object cấu hình đơn giản, một hàm nhận Config đầy đủ thường là đủ — chỉ dùng builder có kiểu khi API thật sự cần gọi từng bước.
Tóm tắt
| Pattern | Biến bug nào thành lỗi compile |
|---|---|
as const + satisfies Record<K, V> | Quên cập nhật bảng tra khi thêm giá trị mới |
Discriminated union + assertNever | Quên xử lý một trạng thái |
| Bảng chuyển trạng thái có kiểu | Chuyển trạng thái không hợp lệ |
| Event map | Gõ sai tên sự kiện, sai payload |
| Builder generic | Quên thiết lập trường bắt buộc |
Comments