TypeScript type guard และ exhaustiveness



บทที่ 7 narrow ด้วย typeof / in / instanceof — บทนี้สร้าง narrowing logic ของเราเอง

user-defined type guard — x is T

ฟังก์ชันที่ return boolean แต่ประกาศ return type เป็น arg is Type:

interface Cat {
  meow(): void;
}
interface Dog {
  bark(): void;
}

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

function handle(animal: Cat | Dog) {
  if (isCat(animal)) {
    animal.meow();     // animal: Cat ตรงนี้
  } else {
    animal.bark();     // animal: Dog
  }
}

animal is Cat = “ถ้าฟังก์ชันนี้ return true TS จะถือว่า argument เป็น Cat“

type guard ที่ใช้บ่อย

// non-null
function isDefined<T>(value: T | null | undefined): value is T {
  return value !== null && value !== undefined;
}

const items = [1, null, 2, undefined, 3];
const defined = items.filter(isDefined);   // number[]  ← filter narrow ให้!

// string
function isString(x: unknown): x is string {
  return typeof x === "string";
}

// object with property
function hasId(obj: unknown): obj is { id: string } {
  return (
    typeof obj === "object" &&
    obj !== null &&
    "id" in obj &&
    typeof (obj as { id: unknown }).id === "string"
  );
}

// discriminated union member
function isSuccess<T>(
  result: { ok: true; value: T } | { ok: false; error: string },
): result is { ok: true; value: T } {
  return result.ok;
}

type guard กับ Array.filter

filter ปกติไม่ narrow — ต้อง type guard:

const values: (string | null)[] = ["a", null, "b", null];

const clean1 = values.filter((v) => v !== null);
// clean1: (string | null)[]  ← ยังมี null ใน type!

const clean2 = values.filter((v): v is string => v !== null);
// clean2: string[]           ← narrow แล้ว

// หรือใช้ helper
const clean3 = values.filter(isDefined);   // string[]

assertion function — asserts x is T

ฟังก์ชันที่ throw ถ้าเงื่อนไขไม่จริง (แทน return boolean):

function assert(condition: unknown, message?: string): asserts condition {
  if (!condition) {
    throw new Error(message ?? "Assertion failed");
  }
}

function assertIsString(value: unknown): asserts value is string {
  if (typeof value !== "string") {
    throw new Error(`คาดหวัง string แต่ได้ ${typeof value}`);
  }
}

function process(input: unknown) {
  assertIsString(input);
  input.toUpperCase();   // input: string ตั้งแต่บรรทัดนี้เป็นต้นไป (ไม่ต้อง if)
}

asserts value is string = “ถ้าฟังก์ชันนี้ return (ไม่ throw) TS ถือว่า value เป็น string ต่อจากนี้”

Node มี assert ในตัวที่มี type แบบนี้: import assert from "node:assert"

exhaustiveness check ด้วย never

never = type ที่ไม่มีค่าใด ๆ assign ได้ — ใช้บังคับให้จัดการทุกกรณีของ union:

type Action =
  | { type: "increment"; by: number }
  | { type: "decrement"; by: number }
  | { type: "reset" };

function reducer(state: number, action: Action): number {
  switch (action.type) {
    case "increment":
      return state + action.by;
    case "decrement":
      return state - action.by;
    case "reset":
      return 0;
    default:
      return assertNever(action);   // ← เพิ่ม action type ใหม่แล้วลืม case → error ตรงนี้
  }
}

function assertNever(value: never): never {
  throw new Error(`Unhandled case: ${JSON.stringify(value)}`);
}

ถ้าเพิ่ม { type: "set"; value: number } เข้า Action แล้วลืมเพิ่ม case "set":

Argument of type '{ type: "set"; value: number }' is not assignable to parameter of type 'never'.

compiler บังคับให้เราเพิ่ม case — นี่คือประโยชน์ที่ใหญ่ที่สุดของ discriminated union + never

type predicate ที่ผิด — TS เชื่อคุณ

function isString(x: unknown): x is string {
  return typeof x === "number";   // ผิด! แต่ TS ไม่จับ
}

const x: unknown = 42;
if (isString(x)) {
  x.toUpperCase();   // TS คิดว่า x: string → runtime crash
}

TS ไม่ตรวจ ว่า logic ใน type guard ถูกจริงไหม — เขียนผิดคือ unsafe เท่ากับ as ต้องระวัง

เรื่องที่คนมักพลาด

  • filter((v) => v !== null) แล้วคาดว่า type narrow — ไม่; ต้อง filter((v): v is T => ...) หรือ helper
  • type guard logic ผิด — TS เชื่อ signature ไม่ตรวจ body; ต้องเขียนให้ถูกจริง ๆ
  • assertion function ไม่มี explicit return type — asserts x is T ต้องเขียน; TS infer ไม่ได้
  • assertion function เป็น arrow function — asserts ไม่ทำงานกับ arrow ที่ประกาศเป็น const (ต้อง function declaration หรือ annotate เต็ม)
  • ลืม assertNever ใน default — เพิ่ม variant แล้วไม่รู้ว่าต้องแก้ตรงไหน
  • x is T เมื่อ T ไม่ใช่ subtype ของ arg type — TS อาจ error หรือให้ผลแปลก

สรุป

  • user-defined type guard: function isCat(x): x is Cat { return "meow" in x } — narrow ตาม return
  • ใช้กับ Array.filter((v): v is T => ...) เพื่อให้ผลลัพธ์ narrow (isDefined helper)
  • assertion function: function assert(cond): asserts cond / asserts x is T — throw ถ้าไม่จริง, narrow ต่อจากบรรทัดนั้น
  • exhaustiveness check: assertNever(x: never): never ใน default — compiler บังคับจัดการทุก variant ของ union
  • TS เชื่อ signature ของ type guard ไม่ตรวจ body — เขียนผิด = unsafe

บทถัดไปว่าด้วยการจัดการ null และ undefined — strictNullChecks, ?., ??, non-null assertion !