ਇੱਕ union (A | B) ਦਾ ਮਤਲਬ ਹੈ "A ਜਾਂ B।" ਇੱਕ intersection (A & B) ਦਾ ਮਤਲਬ ਹੈ "ਇੱਕੋ ਸਮੇਂ A ਅਤੇ B ਦੋਵੇਂ।"
ts
= | | ;
: = ;
() { }
ਇੱਕ union (A | B) ਦਾ ਮਤਲਬ ਹੈ "A ਜਾਂ B।" ਇੱਕ intersection (A & B) ਦਾ ਮਤਲਬ ਹੈ "ਇੱਕੋ ਸਮੇਂ A ਅਤੇ B ਦੋਵੇਂ।"
= | | ;
: = ;
() { }
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
}
ਜਦ ਤੱਕ ਤੁਸੀਂ ਇੱਕ union کو narrow ਨਹੀਂ ਕਰਦੇ, ਤੁਸੀਂ ਸਿਰਫ ਉਹ members ਪ੍ਰਾਪਤ ਕਰ ਸਕਦੇ ਹੋ ਜੋ union ਦੇ ਹਰ ਇੱਕ member ਉੱਤੇ ਮੌਜੂਦ ਹਨ — 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 ਓਬਜੈਕਟ types ਨੂੰ compose ਕਰਨ/ਮਿਲਾਉਣ ਲਈ ਵਧੀਆ ਹਨ (ਉਦਾਹਰਨ ਲਈ, ਇੱਕ ਮੌਜੂਦਾ type ਵਿੱਚ props ਜੋੜਨਾ)।
Unions "ਕਈ ਸੰਭਾਵਨਾਵਾਂ ਵਿੱਚੋਂ ਇੱਕ" ਨੂੰ ਮਾਡਲ ਕਰਦੇ ਹਨ — ਸੁਰੱਖਿਤ state modeling ਦੀ ਬੁਨਿਆਦ (ਉਦਾਹਰਨ ਲਈ discriminated unions reducer state ਲਈ), function overloads, ਅਤੇ nullable types (T | null)।
Intersections types ਨੂੰ ਇਕੱਠੇ compose ਕਰਦੇ ਹਨ।
ਇਕੱਠੇ ਉਹ TypeScript ਦੇ type system ਨੂੰ ਉਸ ਕਦਰ expressive ਬਣਾਉਂਦੇ ਹਨ ਕਿ ਅਸਲ data ਨੂੰ ਬਿਲਕੁਲ mirror ਕਰ ਸਕਣ।