Function Parameter के Types
In this page:
function name(param1: type1, param2: type2) {
// body
}
Basic Parameter Types
हर parameter name के बाद एक type जोड़ें, जैसे (name: string), यह specify करने के लिए कि वह parameter exactly किस तरह की value receive करना चाहिए। यह एक plain JavaScript function को एक ऐसे function में बदलता है जहां compiler हर call site actively verify करता है।
उदाहरण: Basic Parameter Types
function greet(name: string) {
console.log(`Hello, ${name}`);
}
greet("Dev");
Multiple Parameters
हर function parameter अपना independent type annotation रख सकता है, तो एक function एक single signature में एक string, एक number, और एक boolean parameter mix कर सकता है। TypeScript हर argument को उसके corresponding parameter के type के against अलग से check करता है।
उदाहरण: Multiple Parameters
function createUser(name: string, age: number, active: boolean) {
console.log(name, age, active);
}
createUser("Isha", 25, true);
Boolean Parameters
Boolean parameters तब उपयोगी हैं जब एक function को एक simple true-or-false decision चाहिए, जैसे एक flag जो control करे कि extra output include करना है या नहीं।
इसे boolean टाइप करना गलती से एक truthy string जैसे "yes" को एक असली boolean के बजाय pass होने से रोकता है।
उदाहरण: Boolean Parameters
function printReport(includeDetails: boolean) {
console.log(includeDetails ? "Full report" : "Summary only");
}
printReport(true);
Object Parameters
Function parameters function को pass किए गए एक object की structure भी describe कर सकते हैं, inline या एक named interface के through। यह exactly document करता है कि function किस properties की उम्मीद उस argument पर करता है, और एक missing या misspelled property तुरंत पकड़ता है।
उदाहरण: Object Parameters
function printUser(user: { name: string; age: number }) {
console.log(user.name, user.age);
}
printUser({ name: "Rohan", age: 30 });
Why Parameter Types Matter
Parameter types functions को काफी सुरक्षित बनाते हैं हर input की expected shape को signature में सीधे document करके। वे TypeScript को एक incorrect call detect करने देते हैं, जैसे arguments को गलत order में या गलत kind के साथ pass करना, code चलने से पहले ही।
उदाहरण: Why Parameter Types Matter
function multiply(a: number, b: number) {
return a * b;
}
// multiply("2", 3); // rejected: caught before running
console.log(multiply(2, 3));
- एक parameter untyped छोड़ना, जैसे
function greet(name), तो यहstrictके under implicitanyबन जाता है। createUser("Isha", true, 25)को गलत order में arguments के साथ call करना, जिसे compiler reject करता है क्योंकि types match नहीं करते।- ज़रूरत से कम या ज़्यादा arguments pass करना, क्योंकि TypeScript को arguments की संख्या parameters से match करनी चाहिए।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: