Trung BìnhTypeScript iconTypeScript

User-defined type guards (type predicates) là gì?

Function type với return type param is Type.

Khi function return true, TS narrow type của param.

typescript
// Type predicate
function isString(val: unknown): val is string {
  return typeof val === 'string';
}

// Sử dụng
function process(val: string | number) {
  if (isString(val)) {
    val.toUpperCase(); // val: string
  } else {
    val.toFixed(2);   // val: number
  }
}

// Thực tế: kiểm tra object shape
interface Cat { meow(): void }
interface Dog { bark(): void }

function isCat(animal: Cat | Dog): animal is Cat {
  return 'meow' in animal;
}

// Array filter với type guard
const items: (string | null)[] = ['a', null, 'b'];
const strings = items.filter((x): x is string => x !== null);
// strings: string[]

Nguy hiểm: TS tin type predicate hoàn toàn, implementation sai sẽ gây runtime bug mà không có compile error.

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

Mở danh sách TypeScript