</>
⌕
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 Date cho class.
  • "swim" in animal kiểm tra property tồn tại.
  • Truthiness (if (x)) loại null/undefined, nhưng cũng loại 0 và "".
  • Type predicate x is T do bạn tự đảm bảo logic đúng; assertion function asserts x is T ném lỗi nếu sai.
🃏 Ôn bằng flashcard