TypeScript จัดการ null และ undefined



strictNullChecks

ด้วย strict เปิด — null และ undefined ไม่ใช่สมาชิกของทุก type:

let name: string = null;        // Error
let name2: string | null = null; // ต้องประกาศชัด

function greet(name: string | undefined) {
  return name.toUpperCase();
  //     ~~~~ 'name' is possibly 'undefined'
}

นี่คือ feature ที่มีค่าที่สุดของ TS — จับ “Cannot read properties of undefined” ก่อน runtime

จัดการ null — narrow ก่อนใช้

function greet(name: string | undefined): string {
  if (name === undefined) {
    return "สวัสดี ผู้ไม่ประสงค์ออกนาม";
  }
  return `สวัสดี ${name.toUpperCase()}`;   // name: string
}

// หรือเช็ค null และ undefined พร้อมกัน
function len(s: string | null | undefined): number {
  if (s == null) return 0;   // == null จับทั้ง null และ undefined
  return s.length;            // s: string
}

// early return
function process(user: User | null) {
  if (!user) return;
  user.doSomething();   // user: User
}

optional chaining — ?.

หยุดและคืน undefined ทันทีถ้าเจอ null/undefined:

interface User {
  name: string;
  address?: {
    city: string;
    zip?: string;
  };
}

const user: User = { name: "อร" };

user.address.city;        // Error: 'user.address' is possibly 'undefined'
user.address?.city;       // string | undefined  — ปลอดภัย
user.address?.zip;        // string | undefined
user.address?.city.toUpperCase();   // string | undefined (ทั้ง chain)

variants:

obj?.prop            // property access
arr?.[index]         // element access
fn?.()               // function call (เรียกถ้า fn ไม่ null)
obj?.method?.()      // chain

// callback ที่อาจไม่มี
onClick?.(event);    // เรียกถ้า onClick มี

?. short-circuit ทั้ง chain:

a?.b.c.d   // ถ้า a เป็น null → คืน undefined ทันที (ไม่แตะ b.c.d)
           // ถ้า a ไม่ null แต่ b เป็น undefined → error (b.c ยังถูกประเมิน)

nullish coalescing — ??

คืนค่าขวาเฉพาะเมื่อซ้ายเป็น null หรือ undefined:

const timeout = config.timeout ?? 5000;
const name = user.name ?? "ไม่ระบุ";

// ต่างจาก || ที่คืนค่าขวาเมื่อซ้ายเป็น falsy ทั้งหมด
const count = 0;
count || 10;    // 10  ← 0 เป็น falsy
count ?? 10;    // 0   ← 0 ไม่ใช่ null/undefined

const text = "";
text || "default";   // "default"
text ?? "default";   // ""

ใช้ ?? เมื่อ 0, "", false เป็นค่าที่ถูกต้อง (ซึ่งมักเป็นเช่นนั้น)

??= assignment:

config.retries ??= 3;   // ตั้ง 3 ถ้า retries เป็น null/undefined

non-null assertion — !

x! บอก TS ว่า “ฉันรู้ว่าตรงนี้ไม่ null/undefined” — ไม่ตรวจตอน runtime:

const el = document.getElementById("app")!;   // HTMLElement (ไม่ใช่ | null)
el.innerHTML = "hello";

const user = users.find((u) => u.id === id)!;  // User (ไม่ใช่ | undefined)

อันตราย — ถ้าผิด → runtime crash โดยไม่มีการเตือน ใช้เมื่อ:

  • มั่นใจจริง ๆ จาก logic ที่ TS ตามไม่ได้
  • prototype / test code

ทางที่ปลอดภัยกว่า:

const el = document.getElementById("app");
if (!el) throw new Error("ไม่พบ #app");
el.innerHTML = "hello";   // narrow แล้ว — ปลอดภัย + error message ชัด

definite assignment assertion — !

field ที่ TS ไม่เห็นว่าถูก init:

class Component {
  private data!: Data;   // ! = "จะ set ก่อนใช้แน่ ๆ" (เช่นใน lifecycle method)

  init() {
    this.data = loadData();
  }
}

ใช้เท่าที่จำเป็น — มักมีวิธี init ใน constructor ที่ดีกว่า

noUncheckedIndexedAccess

flag ที่ทำให้ arr[i] / obj[key] เป็น T | undefined:

// เปิด noUncheckedIndexedAccess
const arr = [1, 2, 3];
const x = arr[10];         // number | undefined  ← ต้องเช็ค
const first = arr[0];      // number | undefined  (แม้ index 0)

const map: Record<string, number> = { a: 1 };
map["b"];                  // number | undefined

ปลอดภัยขึ้นมาก แต่ verbose — หลายทีมเปิด, บางทีมไม่ (เพราะ arr[0] ที่รู้ว่ามีต้องเช็ค)

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

  • || แทน ?? — count || 10 คืน 10 เมื่อ count เป็น 0; ใช้ ?? ถ้า 0/””/false ถูกต้อง
  • x! เพื่อ “แก้ error” — ไม่ตรวจ runtime; narrow ด้วย if แทน (+ error message)
  • a?.b.c — ?. short-circuit ที่ a แต่ b.c ยังประเมินถ้า a ไม่ null; ใช้ a?.b?.c
  • getElementById(...)! ทุกที่ — ถ้า element หายจริง crash เงียบ ๆ; เช็คครั้งเดียวที่ boot
  • ลืมว่า optional property เป็น T | undefined — user.address ที่ประกาศ address? = {...} | undefined
  • if (x) เพื่อเช็ค null — กรอง 0/"" ด้วย; ใช้ if (x != null) ถ้าจะเก็บ falsy อื่น
  • non-null assertion บน array find — find คืน undefined ถ้าไม่เจอ

สรุป

  • strictNullChecks — null/undefined ต้องประกาศชัด (string | null) และ narrow ก่อนใช้
  • ?. optional chaining — หยุด+คืน undefined เมื่อเจอ null (obj?.prop, arr?.[i], fn?.())
  • ?? nullish coalescing — ค่าสำรองเฉพาะ null/undefined (ไม่ใช่ทุก falsy เหมือน ||); ??=
  • x! non-null assertion — บอก TS ว่าไม่ null แต่ไม่ตรวจ runtime (อันตราย); narrow ด้วย if ดีกว่า
  • noUncheckedIndexedAccess — arr[i]/obj[key] เป็น T | undefined (ปลอดภัยขึ้น, verbose ขึ้น)
  • == null จับทั้ง null และ undefined

บทถัดไปว่าด้วย any, unknown, never, void และ type assertion — as vs satisfies vs as const