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/undefinednon-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?.cgetElementById(...)!ทุกที่ — ถ้า 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