Junior #narrowing#type-guard#discriminated-union
Type narrowing và type guard là gì? Discriminated union hoạt động ra sao?
⚡ Trả lời nhanh
Narrowing là việc TypeScript thu hẹp union type trong một nhánh code nhờ `typeof`, `instanceof`, `in`, so sánh bằng, truthiness hoặc type guard tự định nghĩa (`x is T`). Discriminated union dùng một field literal chung (`kind`) để narrow chính xác, kèm kiểm tra `never` để bắt case thiếu.
Ví dụ
main.ts · sửa được
Các cách narrow
typeof x === "string"cho primitive;x instanceof Datecho class."swim" in animalkiểm tra property tồn tại.- Truthiness (
if (x)) loạinull/undefined, nhưng cũng loại0và"". - Type predicate
x is Tdo bạn tự đảm bảo logic đúng; assertion functionasserts x is Tném lỗi nếu sai.