Default parameters in TypeScript functions allow developers to specify default values for function parameters. This feature enhances the flexibility of functions by enabling them to be called with fewer arguments than defined, while still providing meaningful behavior. When a parameter is not provided during a function call, the default value is used instead. This can help prevent errors and reduce the need for additional checks within the function body.
To define a default parameter, you simply assign a value to the parameter in the function signature. Here’s a basic example:
function greet(name: string = "Guest"): string {
return `Hello, ${name}!`;
}
In this example, if the function greet is called without an argument, it will default to "Guest".
Consider a function that calculates the area of a rectangle. You might want to provide default values for width and height:
function calculateArea(width: number = 5, height: number = 10): number {
return width * height;
}
console.log(calculateArea()); // Outputs: 50
console.log(calculateArea(7)); // Outputs: 70
console.log(calculateArea(7, 3)); // Outputs: 21
In this case, if no arguments are passed, the function uses the default values of 5 for width and 10 for height. If only one argument is provided, the other parameter will still use its default value.
undefined, the default value will not be used. This can lead to unexpected behavior:console.log(calculateArea(undefined, 4)); // Outputs: 20, not 50
In this case, passing undefined for the width parameter results in the default height being used, but the width is treated as undefined, leading to a calculation error.
To avoid such issues, consider using a check within the function to handle undefined values explicitly, or use a different approach to manage optional parameters.
In summary, default parameters in TypeScript provide a powerful way to create flexible and robust functions. By following best practices and being mindful of common pitfalls, developers can enhance their code quality and maintainability.