A union (A | B) berarti "A atau B." An intersection (A & B) berarti "A dan B sekaligus."
ts
= | | ;
: = ;
() { }
A union (A | B) berarti "A atau B." An intersection (A & B) berarti "A dan B sekaligus."
= | | ;
: = ;
() { }
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
}
Sampai Anda mempersempit union, Anda hanya dapat mengakses anggota yang ada di setiap anggota union — kompiler melindungi Anda.
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
Intersection hebat untuk menggabungkan/mencampur tipe objek (misalnya menambahkan props ke tipe yang sudah ada).
Unions memodelkan "salah satu dari beberapa kemungkinan" — fondasi pemodelan state yang aman (misalnya discriminated unions untuk reducer state), function overloads, dan nullable types (T | null).
Intersections menggabungkan tipe bersama-sama.
Bersama-sama mereka membuat sistem tipe TypeScript cukup ekspresif untuk mencerminkan data nyata dengan tepat.