|4. Functions मध्ये Types
Chapter 4TypeScript~1 min read

Functions मध्ये Types

Typed Functions

TypeScript मध्ये functions चे parameters आणि return type define करता येतात. यामुळे function कसा call करायचा हे clearly समजतं आणि चुकीचं call केल्यास compile time मध्येच error येतो.

Function types

typescript
// Parameters + return type
function greet(name: string, city: string): string {
  return `नमस्कार ${name}, ${city} मधून!`;
}

// Optional parameter (?)
function createUser(name: string, age?: number): string {
  return age ? `${name}, वय: ${age}` : name;
}

// Default parameter
function welcome(name: string, lang: string = "Marathi"): string {
  return `Welcome to ${lang} tutorial, ${name}!`;
}

// Rest parameters
function sum(...nums: number[]): number {
  return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15

Arrow functions आणि function types

typescript
// Arrow function with types
const multiply = (a: number, b: number): number => a * b;

// Function type as variable type
let mathOperation: (x: number, y: number) => number;
mathOperation = multiply;
mathOperation = (a, b) => a + b; // ✅

// Void return
const log = (msg: string): void => {
  console.log(msg);
};
💡

Return type explicitly लिहणे optional असतं — TypeScript infer करतो. पण explicit लिहणे code readability वाढवतो आणि चुकांपासून वाचवतो.

Key Points — लक्षात ठेवा

  • param: type — parameter types
  • function name(): returnType — return type
  • Optional param: param?: type
  • Default param: param: type = default
  • ...rest: type[] — rest parameters
0/9 chapters पूर्ण