Optional Parameters की जानकारी
In this page:
function name(required: type, optional?: type) {
// body
}
Basic Optional Parameters
एक parameter name के ठीक बाद ? रखना, जैसे (age?: number), उस parameter को optional मार्क करता है, मतलब callers इसे पूरी तरह छोड़ सकते हैं।
Function के अंदर, उस parameter का type automatically undefined include करता है यह reflect करने के लिए कि यह दिया नहीं भी गया हो सकता है।
उदाहरण: Basic Optional Parameters
function greet(name: string, age?: number) {
console.log(name, age);
}
greet("Meera");
Optional Numbers
Optional numeric parameters तब उपयोगी हैं जब एक function का एक sensible default behavior हो लेकिन वह एक extra numeric setting भी support करे, जैसे एक optional precision या limit। जिन callers को उस level का control नहीं चाहिए वे इसे simply omit कर सकते हैं।
उदाहरण: Optional Numbers
function roundValue(value: number, precision?: number) {
return precision === undefined ? Math.round(value) : Number(value.toFixed(precision));
}
console.log(roundValue(3.14159), roundValue(3.14159, 2));
Checking Optional Values
चूंकि एक optional parameter undefined हो सकता है, इसे किसी ऐसे operation में उपयोग करने से पहले जांचा जाना चाहिए जिसे एक concrete value चाहिए, जैसे arithmetic या एक method call।
TypeScript का control-flow analysis वह check होने के बाद type को undefined से narrow कर देता है।
उदाहरण: Checking Optional Values
function printAge(age?: number) {
if (age !== undefined) {
console.log(age + 1);
} else {
console.log("Age not provided");
}
}
printAge();
Required Before Optional
Required parameters को एक function की parameter list में हमेशा optional वालों से पहले आना चाहिए, क्योंकि TypeScript को unambiguously जानना होता है कि कौन से arguments किन parameters से corresponds करते हैं। आप एक optional parameter के बाद एक required parameter नहीं रख सकते।
उदाहरण: Required Before Optional
function createUser(name: string, age?: number) {
console.log(name, age);
}
// function bad(age?: number, name: string) {} // rejected: optional before required
createUser("Yusuf");
When to Use Optional Parameters
Optional parameters तब चमकते हैं जब एक function default रूप से एक common, simple use case cover करता हो लेकिन कम common scenarios के लिए extra configuration भी support करता हो। यह common call site को छोटा रखता है जबकि फिर भी ज़रूरत पड़ने पर ज़्यादा detailed calls allow करता है।
उदाहरण: When to Use Optional Parameters
function search(term: string, caseSensitive?: boolean) {
console.log(`Searching for "${term}"`, caseSensitive ? "(case sensitive)" : "");
}
search("typescript");
- एक optional
age?: numberको arithmetic में बिना पहलेundefinedके लिए check किए उपयोग करना। - एक optional parameter को एक required parameter से पहले रखना, जैसे
(age?: number, name: string), जो एक error है। age?: numberको एक default value के साथ confuse करना, तो missing argumentundefinedही रहता है।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: