TypeScript intersection และการประกอบ type
intersection — A & B
A & B = ค่าที่มี property ครบทั้ง A และ B:
interface HasName {
name: string;
}
interface HasAge {
age: number;
}
type Person = HasName & HasAge;
const p: Person = {
name: "อร",
age: 25,
}; // ต้องมีทั้ง name และ ageunion เทียบ intersection
type A = { a: string };
type B = { b: number };
type Union = A | B; // มี a อย่างเดียว, b อย่างเดียว, หรือทั้งคู่
type Inter = A & B; // ต้องมีทั้ง a และ b
const u1: Union = { a: "x" }; // OK
const u2: Union = { b: 1 }; // OK
const i1: Inter = { a: "x" }; // Error: ขาด b
const i2: Inter = { a: "x", b: 1 }; // OKจำง่าย: | = “หรือ” (ตัวเลือกมากขึ้น, ใช้ได้น้อยลง), & = “และ” (ข้อกำหนดมากขึ้น, มี member รวมกัน)
ประกอบ type จากชิ้นเล็ก
interface Timestamps {
createdAt: Date;
updatedAt: Date;
}
interface SoftDelete {
deletedAt: Date | null;
}
interface Identifiable {
id: string;
}
type User = Identifiable & Timestamps & {
name: string;
email: string;
};
type Post = Identifiable & Timestamps & SoftDelete & {
title: string;
body: string;
};reuse “ความสามารถ” ข้าม type — เหมือน mixin
intersection กับ function
type Logger = {
log: (msg: string) => void;
};
type Timestamped = {
timestamp: () => number;
};
type TimestampedLogger = Logger & Timestamped;
const tl: TimestampedLogger = {
log: (msg) => console.log(msg),
timestamp: () => Date.now(),
};intersection กับ generic — pattern ที่ใช้บ่อย
// เพิ่ม field ให้ type ใด ๆ
type WithId<T> = T & { id: string };
type UserInput = { name: string; email: string };
type User = WithId<UserInput>;
// { name: string; email: string; id: string }
// props + extra
type PropsWithChildren<P> = P & { children?: React.ReactNode };กับดัก: property ชนกัน
ชนกันด้วย type ที่ compatible → narrow ลง
type A = { value: string | number };
type B = { value: string };
type C = A & B;
// C.value: string (intersection ของ string|number กับ string = string)ชนกันด้วย type ที่ incompatible → never
type A = { value: string };
type B = { value: number };
type C = A & B;
// C.value: string & number = never
const c: C = { value: "x" }; // Error
const c2: C = { value: 1 }; // Error
// C ไม่มีทางสร้างได้เลย — value ต้องเป็นทั้ง string และ number พร้อมกัน (เป็นไปไม่ได้)intersection ของ primitive type ที่ต่างกัน = never — object ที่มี field แบบนั้นสร้างไม่ได้ ระวังตอน & type ที่มี field ชื่อเดียวกัน
interface extends vs type intersection
// interface extends — ให้ error ที่ดีกว่าเมื่อ conflict
interface Base { x: number }
interface Derived extends Base {
x: string; // Error: Interface 'Derived' incorrectly extends 'Base'. Type 'string' is not assignable to type 'number'.
}
// type intersection — เงียบ ๆ กลายเป็น never
type Base = { x: number };
type Derived = Base & { x: string }; // ไม่ error ที่นี่ — Derived.x เป็น neverinterface extends จับ conflict ได้ตอนประกาศ; type & ทำ never เงียบ ๆ (เจอตอนใช้)
เมื่อไรใช้ union vs intersection
| ต้องการ | ใช้ |
|---|---|
| ค่าเป็นอย่างใดอย่างหนึ่ง (state, result, input variant) | A | B |
| ค่ามีทุกความสามารถ (ประกอบ mixin, เพิ่ม field) | A & B |
| discriminated union (หลายกรณี) | | + literal tag |
| props + extra (React), model + timestamps | & |
เรื่องที่คนมักพลาด
- สับสน
&กับ|—&= ต้องมีครบทั้งสอง,|= อย่างใดอย่างหนึ่ง &type ที่มี field ชื่อเดียวกัน type ต่างกัน — field กลายเป็นnever(เช่น{x: string} & {x: number})- คิดว่า
A & Bให้ทางเลือก — มันให้ข้อกำหนดรวม (ต้องมีทุก property) - ใช้
type &แทนinterface extendsเมื่อต้องการจับ conflict —interface extendsดีกว่า &union type —(A | B) & Cdistribute เป็น(A & C) | (B & C)— ผลอาจไม่ตามคาด- สร้าง intersection ยักษ์ — อ่านยาก, error message ยาว; ประกอบพอเหมาะ
สรุป
A & B= intersection — ค่าต้องมี property ครบทั้งสอง (member รวมกัน)- ตรงข้าม
A | B(union) = อย่างใดอย่างหนึ่ง (member ที่มีร่วมกันเท่านั้น จนกว่า narrow) - ใช้
&ประกอบ type จากชิ้นเล็ก (“ความสามารถ”):Identifiable & Timestamps & {...} - generic pattern:
type WithId<T> = T & { id: string } - field ชนกันด้วย type incompatible →
never(สร้าง object ไม่ได้) interface extendsจับ conflict ตอนประกาศ;type &ทำ never เงียบ ๆ
บทถัดไปว่าด้วย generics — type parameter, constraint และ default — เครื่องมือที่ทำให้ type reuse ได้