TypeScript supports optional parameters in functions by allowing you to specify a question mark ‘?‘ after the parameter name. When a parameter is marked as optional, it means that you can omit that parameter when calling the function, and if it is not provided, it will be assigned the value ‘undefined‘.
Here’s an example:
function greet(name: string, age?: number): string {
if (age === undefined) {
return `Hello, ${name}!`;
} else {
return `Hello, ${name}! You are ${age} years old.`;
}
}
In this example, the ‘age‘ parameter is marked as optional with the ‘?‘ symbol. This means that you can call the ‘greet‘ function with one or two arguments:
console.log(greet("John")); // Output: Hello, John!
console.log(greet("John", 25)); // Output: Hello, John! You are 25 years old.
You can also use default parameter values in TypeScript functions. Default values allow you to specify a default value for an optional parameter. If the parameter is not provided, the function will use the default value you specified. Here’s an example using default values:
function greetWithDefault(name: string, age: number = 30): string {
return `Hello, ${name}! You are ${age} years old.`;
}
Now, if you omit the ‘age‘ parameter when calling the ‘greetWithDefault‘ function, it will use the default value of ‘30‘:
console.log(greetWithDefault("John")); // Output: Hello, John! You are 30 years old.
console.log(greetWithDefault("John", 25)); // Output: Hello, John! You are 25 years old.
In summary, TypeScript supports optional parameters by using the ? symbol after a parameter’s name and by allowing you to provide default values for optional parameters. This enables you to create more flexible functions that can be called with varying numbers of arguments.