Start Coding

Topics

Optional and Default Parameters in TypeScript

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

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

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.

Combining Optional and Default Parameters

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.

Best Practices

  • Place optional parameters after required parameters in the function signature.
  • Use default parameters for values that are commonly used or have a logical default.
  • Be cautious with null or undefined as default values, as they can lead to unexpected behavior.
  • Consider using Union Types with optional parameters for more precise type checking.

Considerations

When working with optional and default parameters, keep these points in mind:

  • Optional parameters are always of type T | undefined, where T is the declared type.
  • Default parameters do not create optional parameters; they provide a fallback value.
  • Using Function Overloading can sometimes be a better alternative for complex scenarios.

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.