Union के Types
In this page:
let variable: type1 | type2;
type Alias = type1 | type2 | type3;
Basic Union Types
एक union type दो या ज़्यादा types के बीच | symbol रखकर बनता है, जैसे string | number। उस union type के साथ declared एक variable listed types में से किसी एक से match करने वाली value रख सकता है, पर एक समय में सिर्फ एक।
उदाहरण: Basic Union Types
let id: string | number;
id = 101;
console.log(id);
id = "abc101";
console.log(id);
Union Types with Objects
Union types पूरी तरह अलग possible object shapes represent कर सकते हैं, सिर्फ primitives नहीं, जैसे एक value जो या तो एक Cat या एक Dog object हो। जब union में objects की properties अलग हों, union को किसी भी ऐसी चीज़ को access करने से पहले narrow किया जाना चाहिए जो हर member में shared न हो।
उदाहरण: Union Types with Objects
type Cat = { kind: "cat"; meow: () => void };
type Dog = { kind: "dog"; bark: () => void };
let pet: Cat | Dog = { kind: "dog", bark: () => console.log("Woof") };
console.log(pet.kind);
Union Types with Literal Values
एक union general types के बजाय literal values से भी बन सकता है, एक variable को allowed values के एक specific, fixed set में से एक तक restrict करते हुए, जैसे small | medium | large।
यह status, direction, या size जैसे options model करने का एक common और precise तरीका है।
उदाहरण: Union Types with Literal Values
let size: 'small' | 'medium' | 'large';
size = 'medium';
console.log(size);
Narrowing a Union
जब एक value union का कोई भी member हो सकता है, TypeScript इसे typeof या एक equality comparison जैसे runtime checks उपयोग करके narrow कर सकता है। एक बार narrowed branch के अंदर, TypeScript exactly समझता है कि union का कौन सा specific member अभी in play है और matching operations allow करता है।
उदाहरण: Narrowing a Union
function printId(id: string | number) {
if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id.toFixed(0));
}
}
printId(42);
Union Types in Function Parameters
Union types function parameters में बहुत common हैं जब एक function कई अलग तरह के inputs accept करने के लिए designed हो, जैसे एक formatter जो string और number values दोनों handle करता हो।
Function body फिर parameter को narrow करता है और हर possible case को appropriately handle करता है।
उदाहरण: Union Types in Function Parameters
function format(value: string | number): string {
return typeof value === "string" ? value : value.toFixed(2);
}
console.log(format(3.14159), format("hello"));
- एक
string | numbervariable पर एक string method call करना बिना इसे पहले narrow किए। Cat | Dogपरpet.barkaccess करना बिनाkindcheck किए, क्योंकि सिर्फ shared members allowed हैं।- Union
A | Bको intersectionA & Bके साथ confuse करना।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: