0
0
Typescriptprogramming~5 mins

Optional parameters in Typescript

Choose your learning style9 modes available
Introduction

Optional parameters let you call a function without giving all the details every time. This makes your code simpler and more flexible.

When a function can work with or without some information.
When you want to give a default behavior if some details are missing.
When you want to avoid writing many versions of the same function.
When you want to make your code easier to read and use.
When you want to handle extra options without forcing them.
Syntax
Typescript
function functionName(param1: type, param2?: type) {
  // function body
}

The question mark ? after a parameter name means it is optional.

Optional parameters must come after all required parameters.

Examples
This function greets a person and optionally mentions their age.
Typescript
function greet(name: string, age?: number) {
  if (age !== undefined) {
    console.log(`Hello ${name}, you are ${age} years old.`);
  } else {
    console.log(`Hello ${name}`);
  }
}
If the second number is missing, it doubles the first number.
Typescript
function multiply(a: number, b?: number) {
  return b !== undefined ? a * b : a * 2;
}
Sample Program

This program describes a pet by name and optionally by type. If the type is missing, it just says it is a pet.

Typescript
function describePet(name: string, type?: string) {
  if (type !== undefined) {
    console.log(`${name} is a ${type}.`);
  } else {
    console.log(`${name} is a pet.`);
  }
}

describePet("Buddy", "dog");
describePet("Mittens");
OutputSuccess
Important Notes

Optional parameters are useful to avoid errors when some information is not given.

Inside the function, check if the optional parameter exists before using it.

Summary

Optional parameters let you skip some inputs when calling functions.

They must be placed after required parameters.

Use them to make your functions flexible and easier to use.