Skip to main content

Archive

Show more

Optional and Default Parameters Use in TypeScript

Optional and Default Parameters Use in TypeScript

TypeScript allows you to define functions with optional and default parameters, providing greater flexibility in function calls. Optional parameters are not required when the function is called, while default parameters have default values if not provided.


Optional Parameters

Optional parameters are indicated with a question mark (?) after the parameter name. They must be placed after required parameters in the function signature.


function greet(name: string, greeting?: string): string {
  if (greeting) {
    return `${greeting}, ${name}!`;
  } else {
    return `Hello, ${name}!`;
  }
}

console.log(greet("Alice")); // Output: Hello, Alice!
console.log(greet("Bob", "Hi")); // Output: Hi, Bob!

Default Parameters

Default parameters allow you to specify a default value for a parameter. If the caller does not provide an argument for a default parameter, the default value is used.


function greet(name: string, greeting: string = "Hello"): string {
  return `${greeting}, ${name}!`;
}

console.log(greet("Alice")); // Output: Hello, Alice!
console.log(greet("Bob", "Hi")); // Output: Hi, Bob!

Combining Optional and Default Parameters

You can combine optional and default parameters in the same function. This is useful for providing flexibility in how the function can be called.


function greet(name: string, greeting: string = "Hello", punctuation?: string): string {
  let message = `${greeting}, ${name}`;
  if (punctuation) {
    message += punctuation;
  } else {
    message += "!";
  }
  return message;
}

console.log(greet("Alice")); // Output: Hello, Alice!
console.log(greet("Bob", "Hi")); // Output: Hi, Bob!
console.log(greet("Charlie", "Hey", "?")); // Output: Hey, Charlie?

Use Cases for Optional and Default Parameters

Optional and default parameters are particularly useful in the following scenarios:

  • Providing default behavior while allowing customization
  • Making functions more flexible and user-friendly
  • Reducing the need for multiple function overloads

Conclusion

Optional and default parameters enhance the flexibility and usability of functions in TypeScript. By understanding how to use these features effectively, you can create more robust and user-friendly APIs. Whether you need to provide default behavior or optional functionality, TypeScript's support for optional and default parameters makes it easier to write clean and maintainable code.

Comments