Learn how to define functions with optional and default parameters in TypeScript. Understand the syntax, behavior, and best practices for using these features to create flexible and robust functions.
In TypeScript, functions are a fundamental building block for creating reusable and modular code. As you design functions, you may encounter scenarios where certain parameters are not always required, or where you want to provide default values for parameters when they are not supplied. This is where optional and default parameters come into play.
Optional parameters allow you to define parameters that are not mandatory when calling a function. This is particularly useful when you want to provide flexibility in how a function is used. To declare a parameter as optional, you append a question mark (?
) to the parameter name in the function signature.
function greet(name: string, age?: number): string {
if (age !== undefined) {
return `Hello, ${name}. You are ${age} years old.`;
}
return `Hello, ${name}.`;
}
In this example, the age
parameter is optional. When calling the greet
function, you can choose to provide the age
parameter or omit it entirely.
console.log(greet("Alice")); // Output: Hello, Alice.
console.log(greet("Bob", 30)); // Output: Hello, Bob. You are 30 years old.
As demonstrated, the function behaves differently based on whether the optional parameter is provided.
Default parameters allow you to specify a default value for a parameter. If the caller does not provide a value for that parameter, the default value is used. This feature simplifies function calls and reduces the need for additional logic to handle missing values.
function calculatePrice(price: number, tax: number = 0.1): number {
return price + price * tax;
}
Here, the tax
parameter has a default value of 0.1
. If no value is provided for tax
, the function uses the default value.
console.log(calculatePrice(100)); // Output: 110
console.log(calculatePrice(100, 0.2)); // Output: 120
The function calculates the price using the default tax rate when no tax value is specified.
While both optional and default parameters offer flexibility, they serve different purposes and have distinct behaviors.
undefined
within the function.undefined
because the default value is assigned.function printMessage(message: string, prefix?: string, suffix: string = "!"): string {
if (prefix) {
return `${prefix} ${message}${suffix}`;
}
return `${message}${suffix}`;
}
console.log(printMessage("Welcome")); // Output: Welcome!
console.log(printMessage("Welcome", "Hello")); // Output: Hello Welcome!
console.log(printMessage("Welcome", undefined, "?")); // Output: Welcome?
In this example, prefix
is optional, and suffix
has a default value. Notice how you can explicitly pass undefined
to skip the optional parameter and use the default value for the next parameter.
When combining optional and default parameters, the order in which you declare them matters. Typically, optional parameters should be placed after required parameters, and default parameters can be placed anywhere, but it’s common to place them after required parameters as well.
function createUser(username: string, isAdmin: boolean = false, age?: number): string {
let userInfo = `User: ${username}, Admin: ${isAdmin}`;
if (age !== undefined) {
userInfo += `, Age: ${age}`;
}
return userInfo;
}
console.log(createUser("John")); // Output: User: John, Admin: false
console.log(createUser("Jane", true)); // Output: User: Jane, Admin: true
console.log(createUser("Doe", false, 25)); // Output: User: Doe, Admin: false, Age: 25
In this function, isAdmin
has a default value, and age
is optional. This order allows for flexible function calls.
Experiment with the following exercises to reinforce your understanding of optional and default parameters:
greet
function to include an optional greeting
parameter that defaults to “Hello”.calculateTotal
that takes a price
, an optional discount
, and a default tax
of 0.05. Calculate the total price after applying the discount and tax.formatDate
that accepts a date
and an optional format
parameter. If no format is provided, use a default format of “YYYY-MM-DD”.To better understand how optional and default parameters interact, consider the following flowchart that illustrates the decision-making process within a function:
graph TD; A[Start] --> B{Is optional parameter provided?} B -->|Yes| C[Use provided value] B -->|No| D{Is default parameter provided?} D -->|Yes| E[Use default value] D -->|No| F[Parameter is undefined] C --> G[Execute Function] E --> G F --> G G --> H[End]
This flowchart shows how the function determines which value to use for each parameter based on whether they are optional or have default values.
For more information on functions in TypeScript, consider exploring the following resources:
?
and can be omitted in function calls.By understanding and applying these concepts, you’ll be able to write more versatile and maintainable TypeScript functions.