0
0
Typescriptprogramming~3 mins

Why Optional parameters in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one function that adapts to many situations without extra hassle?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
function greet(name: string) {
  if (name === undefined) {
    console.log('Hello!');
  } else {
    console.log('Hello, ' + name + '!');
  }
}
After
function greet(name?: string) {
  console.log(`Hello${name ? ', ' + name : ''}!`);
}
What It Enables

Optional parameters make your functions flexible and your code cleaner, so you can handle many cases with less effort.

Real Life Example

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.

Key Takeaways

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.