Trung BìnhTypeScript iconTypeScript

Type narrowing là gì? Các cách narrow type trong TypeScript?

Type narrowing là thu hẹp type trong code branch dựa trên kiểm tra.

TypeScript tự động narrow trong if/else, switch, ternary.

typescript
function process(val: string | number | Date) {
  if (typeof val === 'string') return val.toUpperCase(); // typeof
  if (val instanceof Date) return val.toISOString();    // instanceof
  return val.toFixed(2);                                 // number
}

// User-defined type guard
function isUser(obj: unknown): obj is User {
  return typeof obj === 'object' && obj !== null && 'id' in obj;
}

Xem toàn bộ TypeScript cùng filter theo level & chủ đề con.

Mở danh sách TypeScript