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ను సంకుచితం చేసే వరకు, union యొక్క ప్రతి సభ్యపై ఉన్న సభ్యులను మాత్రమే యాక్సెస్ చేయవచ్చు — కంపైలర్ మిమ్మల్ని రక్షిస్తుంది.
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 ఆబ్జెక్ట్ రకాలను కంపోజ్ చేయడానికి/మిక్స్ చేయడానికి గొప్పవి (ఉదా. ఇప్పటికే ఉన్న రకకు props జోడించడం).
Unions "అనేక సంభావ్యతల్లో ఒకటి" మోడల్ చేస్తాయి — సురక్షితమైన స్థితి మోడలింగ్ (ఉదా. reducer స్థితి కోసం వివక్ష union), ఫంక్షన్ ఓవర్లోడ్లు మరియు nullable రకాల (T | null) ఆధారం.
Intersections రకాలను కలుపుతాయి.
ఒకచేటిగా, అవి TypeScript యొక్క రకం వ్యవస్థను వ్యక్తీకరించేందుకు తగిన విధంగా వాస్తవ డేటాను ఖచ్చితంగా ప్రతిబింబించేలా చేస్తాయి.