TypeScript - Optional Parameters



The optional parameters in TypeScript allow us to specify function parameters may or may not be provided when calling the function.

When a function is called without argument value for optional parameter, the default value of optional parameter is set to undefined. So inside the function body, we need to handle the optional parameter.

A parameter can be made optional by adding a question mark after the its name in function definition.

Syntax

The syntax to defined a function with optional parameters in TypeScript is as follows −

function functionName(para1:type1, para2?:type2): returnType{
   // function body
}

In the above syntax, the function functionName is defined with two parameters − para1 and para2. The first parameter para1 is a required parameter and second parameter para2 is optional parameter.

You can define a function with more than one optional parameters but the optional parameters must be the last parameters.

JavaScript supports the optional parameters by default because in JavaScript, you can call a function without passing any argument even if it specifies the parameters.

Examples

Let’s understand the function optional parameters with the help of some programming examples in TypeScript.

Example: Using Optional Function Parameters

In the example below, the function sum accepts three parameters, x, y, and z. The first two parameters x, and y are required parameters and the third parameter z is optional parameter.

We first check if the optional parameter is true or not. If it is passed, we return the sum of all parameters else we return the sum of only required parameters. Look at the example.

function sum(x: number, y: number, z?: number): number {
   if (z){
      return x + y + z;
   }
   else{
      return x + y;
   }
}
console.log(sum(2,3));
console.log(sum(2,3,5));

On compiling, the above TypeScript code will be converted to the following JavaScript code.

function sum(x, y, z) {
    if (z) {
        return x + y + z;
    }
    else {
        return x + y;
    }
}
console.log(sum(2, 3));
console.log(sum(2, 3, 5));

The output of the above example code is as follows −

5
10

Notice when we call the sum function with only two arguments (without optional parameter), the if condition becomes false. The default value of an optional parameter (missing argument) is undefined.

Example: Type Guards for Option Parameters

We can use a type guard to check if the parameter has a valid value before using it.

In the below example, we use type guard typeof age === 'number' to check if age has a value before using it.

function greet(name: string, age?: number): void {
  if (typeof age === 'number') {
    console.log(`You are ${age} years old.`);
  }
}
greet('Shahid', 35);

On compiling, it will produce the following JavaScript code.

function greet(name, age) {
    if (typeof age === 'number') {
        console.log(`You are ${age} years old.`);
    }
}
greet('Shahid', 35);

The output of the above example code is as follows −

You are 35 years old.

Example: Optional parameters should be last parameters

The optional parameters must be placed after the required parameters in the parameter list.

function add (x?: number, y: number = 30){
   return x + y;
}
console.log(add(2,3));

In the above example, the optional parameter is put before the required parameter. The TypeScript compiler will throw the following error −

'x' is possibly 'undefined'.

Example: Optional parameters can't have default values

An optional parameter can’t be initialized with a default value. In the below example, we have initialized the parameter y optional with a default value, 30.

function add (x: number, y?: number = 30){
   return x + y;
}
console.log(add(2,3));

The TypeScript compiler will show the following error −

Parameter cannot have question mark and initializer.

The error shows that we can’t assign a parameter as both optional and default.

How to deal with it? The default parameters are optional parameters also.

Example: Default values for optional parameters

A default parameter is automatically an optional parameter. The default values are used for missing arguments if the function is called with missing values.

function greet(name: string, age: number = 35): void {
  console.log(`Hello, ${name}!`);
  console.log(`You are ${age} years old.`);
}
greet('Shahid');

In the above example, we define the function greet with two parameters − name and age. The second parameter, age is initialized with default value. The parameter age works here as optional parameter.

On compiling, it will generate the following JavaScript code.

function greet(name, age = 35) {
    console.log(`Hello, ${name}!`);
    console.log(`You are ${age} years old.`);
}
greet('Shahid');

The output of the above example code is as follows −

Hello, Shahid!
You are 35 years old.
Advertisements