A union (A | B) tegese "salah siji A utawa B." An intersection (A & B) tegese "loro A lan B ing sawijining wektu."
ts
= | | ;
: = ;
() { }
A union (A | B) tegese "salah siji A utawa B." An intersection (A & B) tegese "loro A lan B ing sawijining wektu."
= | | ;
: = ;
() { }
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
}
Sampe sampeyan narrow sawijining union, sampeyan mung bisa ngakses anggota sing ana ing saben anggota saka union — compiler njaga sampeyan.
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 bagus kanggo nyusun/nggabungake tipe obyek (contone, nambahake props marang tipe sing wis ana).
Unions model "salah siji saka pirang-pirang kemungkinan" — fondasi saka state modeling sing aman (contone discriminated unions kanggo reducer state), function overloads, lan nullable types (T | null).
Intersections nggabungake tipe-tipe bebarengan.
Saktine loro-lorone, padha ngajaake TypeScript kang sistem tipe cukup expressive kanggo ngreca data nyata kanthi tepat.