0
0
Typescriptprogramming~3 mins

Why Default parameters with types in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your functions could handle missing inputs all by themselves, without extra code?

The Scenario

Imagine you are writing a function that greets users. You want to say "Hello" to a user, but if no name is given, you want to say "Hello, Guest". Without default parameters, you have to write extra code to check if the name was provided every time.

The Problem

This manual way is slow and error-prone because you must always remember to check if the input exists. If you forget, your program might crash or behave unexpectedly. It also makes your code longer and harder to read.

The Solution

Default parameters with types let you set a default value right in the function signature. This means if no value is passed, the default is used automatically. It keeps your code clean, safe, and easy to understand.

Before vs After
Before
function greet(name: string | undefined) {
  if (name === undefined) {
    name = "Guest";
  }
  console.log(`Hello, ${name}`);
}
After
function greet(name: string = "Guest") {
  console.log(`Hello, ${name}`);
}
What It Enables

This makes your functions simpler and safer, so you can focus on what your program should do instead of checking inputs all the time.

Real Life Example

When building a website, you might have a function to show user profiles. If the user doesn't provide a profile picture, you can use a default image automatically using default parameters with types.

Key Takeaways

Default parameters save you from writing extra checks.

They make your code cleaner and easier to read.

Typing default parameters helps catch errors early.