Function Parameter Types
A function parameter is a variable that receives a value when a function is called.
Basic Function
function greet(name: string) {
console.log("Hello " + name);
}
greet("Hemant");
Function Return Types
Basic Return Type
function add(a: number, b: number): number {
return a + b;
}
let result = add(10, 20);
console.log(result); // 30
Optional Parameters
An optional parameter is a parameter that a function caller is not required to provide.
In TypeScript, we use the ? symbol to make a parameter optional.
function greet(name: string, age?: number): void {
console.log("Name:", name);
console.log("Age:", age);
}
greet("Rahul");
greet("Amit", 25);
Optional Parameters Must Come After Required Parameters
Correct:
function student(name: string, age?: number) {
console.log(name, age);
}
Default Parameters
A default parameter allows you to assign a default value to a function parameter.
If the caller does not provide that argument, TypeScript uses the default value.
function greet(name: string, message: string = "Welcome"): void {
console.log(`${message}, ${name}`);
}
greet("Rahul");
greet("Amit", "Good morning");
Rest Parameters
Rest parameters allow a function to accept any number of arguments and collect them into a single array.
Syntax
Use ... before the parameter name.
function add(...numbers: number[]): number {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
console.log(add(10, 20));
console.log(add(10, 20, 30));
console.log(add(10, 20, 30, 40, 50));
Important rules
- A function can have only one rest parameter.
- The rest parameter must be the last parameter.
- Its type must be an array type.