union (A | B) หมายความว่า "A หรือ B" intersection (A & B) หมายความว่า "A และ B พร้อมกันในเวลาเดียวกัน"
ts
= | | ;
: = ;
() { }
function format(x: string | number) {
// x.toFixed(2); // ❌ toFixed doesn't exist on string
if (typeof x === "number") return x.toFixed(2); // ✅ narrowed to number
return x.toUpperCase(); // ✅ here it's a string
}
จนกว่าคุณจะ 缩小 narrowing union คุณสามารถเข้าถึงเฉพาะสมาชิกที่มีอยู่ในสมาชิก ทุกตัว ของ union — compiler ปกป้องคุณ
type Name = { name: string };
type Age = { age: number };
type Person = Name & Age; // must have BOTH name and age
const p: Person = { name: "Ann", age: 30 }; // both required
Intersections เหมาะสำหรับการเขียนโค้ด/ผสมรูปแบบ object types (เช่น การเพิ่ม props ให้กับประเภทที่มีอยู่)
Unions จำลอง "หนึ่งในหลายความเป็นไปได้" — รากฐานของการสร้างแบบจำลองสถานะที่ปลอดภัย (เช่น discriminated unions สำหรับสถานะ reducer), function overloads และ nullable types (T | null)
Intersections รวมประเภทเข้าด้วยกัน
พร้อมกันอยู่นั้น พวกมันทำให้ระบบประเภท TypeScript สามารถแสดงออกเพียงพอที่จะสะท้อนข้อมูลจริงได้อย่างแม่นยำ