What if you could write one function that adapts to many situations without extra hassle?
Why Optional parameters in Typescript? - Purpose & Use Cases
Imagine you are writing a function that greets people. Sometimes you want to say hello with their name, but other times you just want a simple greeting without a name.
If you try to handle this manually, you must write multiple versions of the same function or add complicated checks everywhere. This makes your code long, confusing, and easy to break.
Optional parameters let you write one simple function that can work with or without extra information. You just mark some inputs as optional, and the function knows how to handle missing values smoothly.
function greet(name: string) {
if (name === undefined) {
console.log('Hello!');
} else {
console.log('Hello, ' + name + '!');
}
}function greet(name?: string) {
console.log(`Hello${name ? ', ' + name : ''}!`);
}Optional parameters make your functions flexible and your code cleaner, so you can handle many cases with less effort.
Think about a messaging app where you can send a message with or without a subject line. Optional parameters let the sendMessage function work perfectly in both cases.
Optional parameters let you skip some inputs when calling functions.
This reduces repetitive code and complex checks.
Your functions become easier to read and maintain.