void का Type
In this page:
function name(): void {
// no return value
}
Basic Void Function
एक function explicitly void को इसके return type के रूप में declare कर सकता है यह signal करने के लिए कि यह एक action perform करता है लेकिन कोई usable value return नहीं करता। यह उस function का TypeScript equivalent है जो बस कुछ करता है और implicitly undefined return करता है।
उदाहरण: Basic Void Function
function logMessage(): void {
console.log("This is a message");
}
logMessage();
Parameters के साथ Void
Void functions अब भी parameters पूरी तरह normally accept कर सकते हैं, क्योंकि void type सिर्फ यह describe करता है कि वापस क्या आता है, यह नहीं कि क्या जाता है। एक function तीन typed parameters ले सकता है और फिर भी void return करने के लिए declared हो सकता है।
उदाहरण: Void with Parameters
function logSum(a: number, b: number, label: string): void {
console.log(`${label}: ${a + b}`);
}
logSum(2, 3, "Sum");
Void और Return Values
void return करने के लिए declared एक function सिर्फ यह signal करने के लिए है कि यह कोई meaningful result produce नहीं करता, भले ही यह technically under the hood undefined return करे।
एक function जिसका signature एक अलग, non-void return type promise करता है उसे वाकई उस type से match करती एक value provide करनी चाहिए।
उदाहरण: Void and Return Values
function logMessage(): void {
console.log("Just performing an action");
// return "text"; // rejected: doesn't match void
}
logMessage();
Callbacks में Void
Void return types उन callback functions के लिए खासतौर पर common हैं जो एक value compute करने के बजाय एक action perform करते हैं, जैसे event handlers।
forEach जैसे Array methods void return करने के लिए typed callbacks accept करते हैं, क्योंकि callback से कोई भी return value simply ignore हो जाती है।
उदाहरण: Void in Callbacks
let numbers: number[] = [1, 2, 3];
numbers.forEach((n: number): void => {
console.log(n * 2);
});
Void और Function Types
एक function type खुद एक void return value describe कर सकता है, जैसे () => void, एक variable को बिना output produce किए एक action perform करने वाले किसी भी function को hold करने देते हुए। यह exactly वह shape है जो ज़्यादातर event listener और side-effect callbacks लेते हैं।
उदाहरण: Void and Function Types
let onClick: () => void;
onClick = () => console.log("Button clicked");
onClick();
: voiddeclared एक function सेreturn 5जैसी एक value return करना, जो एक error है।- एक
voidfunction का return value उपयोग करना, जैसेconst x = logMessage(), और कुछ useful की उम्मीद करना। voidकोundefinedयाneverके साथ confuse करना, जबvoidका मतलब है कि result उपयोग नहीं होना चाहिए।
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: