TypeScript enhances JavaScript's function capabilities by introducing optional and default parameters. These features allow developers to create more flexible and robust functions, improving code readability and reducing errors.
Optional parameters in TypeScript are denoted by appending a question mark (?) to the parameter name. This syntax allows a function to be called with or without that specific argument.
function greet(name: string, greeting?: string) {
if (greeting) {
return `${greeting}, ${name}!`;
} else {
return `Hello, ${name}!`;
}
}
console.log(greet("Alice")); // Output: Hello, Alice!
console.log(greet("Bob", "Good morning")); // Output: Good morning, Bob!
In this example, the greeting
parameter is optional. The function works whether you provide one or two arguments.
Default parameters allow you to specify a default value for a parameter if no argument is provided or if the argument is undefined
.
function calculateTotal(price: number, taxRate: number = 0.1) {
return price + (price * taxRate);
}
console.log(calculateTotal(100)); // Output: 110
console.log(calculateTotal(100, 0.2)); // Output: 120
Here, taxRate
has a default value of 0.1 (10%). If not specified, this default value is used in the calculation.
You can use both optional and default parameters together for even more flexibility:
function createUser(name: string, age?: number, country: string = "Unknown") {
return `Name: ${name}, Age: ${age ?? "Not provided"}, Country: ${country}`;
}
console.log(createUser("Alice")); // Output: Name: Alice, Age: Not provided, Country: Unknown
console.log(createUser("Bob", 30)); // Output: Name: Bob, Age: 30, Country: Unknown
console.log(createUser("Charlie", 25, "USA")); // Output: Name: Charlie, Age: 25, Country: USA
This function demonstrates the use of both optional and default parameters, providing different levels of information based on the arguments passed.
null
or undefined
as default values, as they can lead to unexpected behavior.When working with optional and default parameters, keep these points in mind:
T | undefined
, where T is the declared type.By mastering optional and default parameters, you can create more versatile functions in TypeScript, leading to cleaner and more maintainable code. These features are particularly useful when designing APIs or libraries where flexibility is key.