In this section, we will explore how to work with optional and default parameters in TypeScript. These features allow you to write more flexible and robust functions by providing default values for parameters and making some parameters optional.
Key Concepts
- Optional Parameters: Parameters that are not required when calling a function.
- Default Parameters: Parameters that have a default value if no value is provided when the function is called.
Optional Parameters
Optional parameters are defined by appending a question mark (?) to the parameter name. This indicates that the parameter is not required when the function is called.
Example
function greet(name: string, age?: number): string {
if (age) {
return `Hello, ${name}. You are ${age} years old.`;
} else {
return `Hello, ${name}.`;
}
}
console.log(greet("Alice")); // Output: Hello, Alice.
console.log(greet("Bob", 25)); // Output: Hello, Bob. You are 25 years old.Explanation
- The
ageparameter is optional. - If
ageis provided, the function includes it in the greeting. - If
ageis not provided, the function omits it from the greeting.
Default Parameters
Default parameters allow you to specify a default value for a parameter. If no value is provided for that parameter when the function is called, the default value is used.
Example
function greet(name: string, age: number = 30): string {
return `Hello, ${name}. You are ${age} years old.`;
}
console.log(greet("Alice")); // Output: Hello, Alice. You are 30 years old.
console.log(greet("Bob", 25)); // Output: Hello, Bob. You are 25 years old.Explanation
- The
ageparameter has a default value of30. - If
ageis not provided, the function uses the default value. - If
ageis provided, the function uses the provided value.
Combining Optional and Default Parameters
You can combine optional and default parameters in a single function. However, optional parameters must come after required parameters, and default parameters can be placed anywhere.
Example
function greet(name: string, age?: number, greeting: string = "Hello"): string {
if (age) {
return `${greeting}, ${name}. You are ${age} years old.`;
} else {
return `${greeting}, ${name}.`;
}
}
console.log(greet("Alice")); // Output: Hello, Alice.
console.log(greet("Bob", 25)); // Output: Hello, Bob. You are 25 years old.
console.log(greet("Charlie", undefined, "Hi")); // Output: Hi, Charlie.Explanation
- The
ageparameter is optional. - The
greetingparameter has a default value of"Hello". - If
ageis not provided, the function omits it from the greeting. - If
greetingis provided, the function uses the provided value.
Practical Exercises
Exercise 1
Create a function calculateTotal that takes three parameters: price (number), quantity (number, optional), and tax (number, default value of 0.1). The function should return the total cost.
function calculateTotal(price: number, quantity?: number, tax: number = 0.1): number {
const qty = quantity ?? 1; // Use 1 if quantity is not provided
return price * qty * (1 + tax);
}
// Test cases
console.log(calculateTotal(100)); // Output: 110
console.log(calculateTotal(100, 2)); // Output: 220
console.log(calculateTotal(100, 2, 0.2)); // Output: 240Solution Explanation
- The
quantityparameter is optional. If not provided, it defaults to1. - The
taxparameter has a default value of0.1. - The function calculates the total cost by multiplying the price, quantity, and tax.
Exercise 2
Create a function createUser that takes three parameters: username (string), email (string, optional), and role (string, default value of "user"). The function should return an object with these properties.
function createUser(username: string, email?: string, role: string = "user"): { username: string, email?: string, role: string } {
return { username, email, role };
}
// Test cases
console.log(createUser("john_doe")); // Output: { username: 'john_doe', role: 'user' }
console.log(createUser("jane_doe", "[email protected]")); // Output: { username: 'jane_doe', email: '[email protected]', role: 'user' }
console.log(createUser("admin_user", "[email protected]", "admin")); // Output: { username: 'admin_user', email: '[email protected]', role: 'admin' }Solution Explanation
- The
emailparameter is optional. - The
roleparameter has a default value of"user". - The function returns an object with the provided properties.
Common Mistakes and Tips
- Order of Parameters: Ensure that optional parameters come after required parameters.
- Default Values: Remember that default values are used only if no value is provided.
- Combining Optional and Default Parameters: Be cautious when combining these features to avoid confusion.
Conclusion
In this section, we learned how to use optional and default parameters in TypeScript to create more flexible and robust functions. We covered the syntax and provided practical examples and exercises to reinforce the concepts. Understanding these features will help you write cleaner and more maintainable code.
TypeScript Course
Module 1: Introduction to TypeScript
- What is TypeScript?
- Setting Up the TypeScript Environment
- Basic Types
- Type Annotations
- Compiling TypeScript
Module 2: Working with Types
Module 3: Advanced Types
Module 4: Functions and Modules
Module 5: Asynchronous Programming
Module 6: Tooling and Best Practices
- Linting and Formatting
- Testing TypeScript Code
- TypeScript with Webpack
- TypeScript with React
- Best Practices
