A union (A | B) tfisser "jew A jew B." An intersection (A & B) tfisser "kemm A u B fl-istess ħin."
ts
= | | ;
: = ;
() { }
A union (A | B) tfisser "jew A jew B." An intersection (A & B) tfisser "kemm A u B fl-istess ħin."
= | | ;
: = ;
() { }
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
}
Sa sa tkun narrow union, tista' taċċessa biss l-membri preżenti fuq kull membru tal-union — il-compiler jipproteġilek.
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
L-Intersections huma kbira għat-tqassim/taħlit ta' tipi ta' oġġetti (eż. iżżid props għal tip eżistenti).
Unions jimmudellaw "waħda minn diversi possibbiltajiet" — il-bażi ta' mudellazzjoni tas-stat sigura (eż. discriminated unions għal reducer state), overloads ta' funzjoni, u tipi nullable (T | null).
L-Intersections jikkombinaw tipi flimkien.
Flimkien jagħmluha s-sistema ta' tipi TypeScript espressiva biżżejjed biex tirrifletti d-data reali b'eżattezza.