TypeScript union type และ narrowing
union type — A | B
let id: string | number;
id = "abc-123"; // OK
id = 42; // OK
id = true; // Error
function printId(id: string | number) {
console.log(id);
}union แปลว่า “เป็นอย่างใดอย่างหนึ่งในนี้” — ใช้ได้เฉพาะ property/method ที่มีทั้งสองฝั่ง:
function printId(id: string | number) {
console.log(id.toUpperCase());
// ~~~~~~~~~~~ Property 'toUpperCase' does not exist on type 'number'
}narrowing — บอก TS ว่าตอนนี้เป็น type ไหน
typeof
function printId(id: string | number) {
if (typeof id === "string") {
console.log(id.toUpperCase()); // id: string ตรงนี้
} else {
console.log(id.toFixed(2)); // id: number ตรงนี้
}
}typeof narrow ได้: "string", "number", "boolean", "object", "function", "undefined", "bigint", "symbol"
equality / ===
function example(x: string | number, y: string | boolean) {
if (x === y) {
// x และ y ต้องเป็น type ที่ overlap ได้ = string
x.toUpperCase(); // x: string
y.toUpperCase(); // y: string
}
}
// narrow กับ literal
function move(direction: "up" | "down" | "left" | "right") {
if (direction === "up") {
// direction: "up"
}
}truthiness
function print(value: string | null | undefined) {
if (value) {
console.log(value.toUpperCase()); // value: string ("" ถูกกรองออกด้วย!)
}
}
// ระวัง: "" 0 NaN ก็ falsy
function len(s: string | null) {
if (s != null) { // เช็ค null และ undefined เท่านั้น
return s.length; // s: string (รวม "")
}
return 0;
}in operator
interface Bird { fly(): void; layEggs(): void; }
interface Fish { swim(): void; layEggs(): void; }
function move(animal: Bird | Fish) {
if ("fly" in animal) {
animal.fly(); // animal: Bird
} else {
animal.swim(); // animal: Fish
}
}instanceof
function logError(error: Error | string) {
if (error instanceof Error) {
console.log(error.message, error.stack); // error: Error
} else {
console.log(error); // error: string
}
}discriminated union — pattern ที่ทรงพลังที่สุด
union ของ object ที่มี field ตัวหนึ่งเป็น literal ต่างกัน (“discriminant” / “tag”):
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rectangle"; width: number; height: number }
| { kind: "triangle"; base: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2; // shape: { kind: "circle"; radius: number }
case "rectangle":
return shape.width * shape.height; // shape มี width, height
case "triangle":
return 0.5 * shape.base * shape.height;
}
}TS narrow อัตโนมัติจาก shape.kind — ในแต่ละ case เข้าถึง property ที่ถูกต้องได้ และ error ถ้าใช้ property ผิดกรณี
exhaustiveness check ด้วย never
function area(shape: Shape): number {
switch (shape.kind) {
case "circle": return Math.PI * shape.radius ** 2;
case "rectangle": return shape.width * shape.height;
case "triangle": return 0.5 * shape.base * shape.height;
default:
const _exhaustive: never = shape; // ถ้าเพิ่ม kind ใหม่แล้วลืม case → error ตรงนี้
throw new Error(`unhandled shape: ${_exhaustive}`);
}
}ถ้าเพิ่ม { kind: "square"; size: number } เข้า Shape แล้วลืมเพิ่ม case — บรรทัด const _exhaustive: never = shape จะ error เพราะ shape ไม่ใช่ never — compiler บังคับให้เราจัดการทุกกรณี
นี่คือเหตุผลที่ discriminated union ดีกว่า class hierarchy สำหรับหลายกรณี — เพิ่ม variant แล้วรู้ทันทีว่าต้องแก้ตรงไหน
union กับ array
const items: (string | number)[] = [1, "two", 3];
const strings = items.filter((x): x is string => typeof x === "string");
// strings: string[] — ต้องใช้ type predicate (บทที่ 23) ให้ filter narrow ได้narrowing ที่ไม่ทำงาน
function example(obj: { data: string | number }) {
if (typeof obj.data === "string") {
doSomethingAsync().then(() => {
obj.data.toUpperCase(); // Error! TS "ลืม" narrowing หลัง callback
});
}
}
// แก้: เก็บลงตัวแปร
const data = obj.data;
if (typeof data === "string") {
doSomethingAsync().then(() => data.toUpperCase()); // OK
}TS narrow ตัวแปร ไม่ใช่ property access ที่อาจเปลี่ยนค่า — เก็บลง const ก่อน
เรื่องที่คนมักพลาด
- ใช้ property ของ union โดยไม่ narrow — ใช้ได้เฉพาะที่มีทั้งสองฝั่ง
if (value)เพื่อเช็ค null — กรอง"",0ออกด้วย; ใช้if (value != null)ถ้าจะเก็บ falsy อื่นtypeof x === "object"แล้วคิดว่าไม่ null —typeof null === "object"- discriminated union ที่ discriminant ไม่ใช่ literal — ต้องเป็น
kind: "circle"ไม่ใช่kind: string - ลืม exhaustiveness check (
never) — เพิ่ม variant แล้วลืม case โดยไม่รู้ตัว - narrowing “หาย” หลัง callback/await — เก็บลง
constก่อน switchบน discriminated union ไม่มีdefault— ถ้าเปิดnoImplicitReturnsจะเตือน แต่ยังพลาด variant ใหม่ได้ ใช้nevercheck
สรุป
A | B— เป็นอย่างใดอย่างหนึ่ง; ใช้ได้เฉพาะ member ที่มีทุกฝั่งจนกว่าจะ narrow- narrow ด้วย:
typeof,===/literal, truthiness (!= nullปลอดภัยกว่าif(x)),in,instanceof - discriminated union — union ของ object ที่มี literal tag (
kind) — narrow ด้วยswitch (x.kind), เข้าถึง property ถูกกรณี - exhaustiveness check:
const _: never = xในdefault— compiler บังคับจัดการทุก variant - narrowing ใช้ได้กับตัวแปร ไม่ใช่ property access ข้าม callback/await — เก็บ
constก่อน
บทถัดไปว่าด้วย literal type และ as const — "a" | "b", widening และการทำ enum-like union