Null और Undefined
In this page:
let variable: type | null = null;
let other: type | undefined = undefined;
Undefined Type
एक variable naturally undefined value रखता है जब इसे कभी कोई value assign नहीं की गई हो, या जब यह explicitly undefined पर set हो। यह JavaScript का, और extension से TypeScript का, default "अभी तक यहां कुछ नहीं है" state है।
उदाहरण: Undefined Type
let username: string | undefined;
console.log(username); // undefined, no value assigned yet
Null Type
null value एक intentionally empty value represent करता है, deliberately code द्वारा set की गई यह मतलब देने के लिए कि "कोई value नहीं है" बजाय "कभी कोई value assign नहीं हुई"। null के रूप में strictly typed एक variable सिर्फ वह एक value ही रख सकता है।
उदाहरण: Null Type
let selected: null = null;
console.log(selected);
Null के साथ Union
एक union type एक normal type को null के साथ combine कर सकता है, Type | null के रूप में लिखा गया, यह signal करने के लिए कि एक value legitimately missing हो सकती है। यह उस value को उपयोग करने वाले किसी भी व्यक्ति को missing case explicitly handle करने के लिए मजबूर करता है, यह assume करने के बजाय कि यह हमेशा present है।
उदाहरण: Union with Null
let city: string | null = null;
city = "Chennai";
console.log(city);
Null और Undefined जांचना
null या undefined हो सकने वाली एक value उपयोग करने से पहले, इसकी presence जांचना TypeScript को बाकी code block के लिए type narrow करने देता है, possibilities से null या undefined हटाते हुए।
यह ऐसे ही है कि TypeScript का control-flow analysis एक guard के बाद manual type assertions की ज़रूरत खत्म करता है।
उदाहरण: Checking Null and Undefined
let city: string | null = null;
if (city !== null) {
console.log(city.toUpperCase());
} else {
console.log("No city set");
}
Nullish Coalescing
nullish coalescing operator, ?? के रूप में लिखा गया, specifically तब एक fallback value provide करता है जब left-hand side null या undefined हो।
पुराने || operator के विपरीत, यह 0 या एक empty string जैसी valid falsy values को सही से untouched छोड़ देता है उन्हें replace करने के बजाय।
उदाहरण: Nullish Coalescing
let count: number | null = null;
let total = count ?? 0;
console.log(total); // 0, since count is null
let zero: number | null = 0;
console.log(zero ?? 99); // 0, since 0 is not null/undefined
- एक
string | undefinedvariable जैसेusername.lengthउपयोग करना बिना पहले इसे check किए, जोstrictNullChecksके तहत fail होता है। nullऔरundefinedको same मानना=== nullउपयोग करके और एक unassignedundefinedmiss करना।nullकोstringtyped एक variable में assign करना और इसके work करने की उम्मीद करना, जब इसेstring | nullचाहिए।
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: