JavaScript Coder

Typescript Optional Parameters

typescript optional parameter typescript optional parameter or default value typescript omit optional parameters typescript parameters

All parameters of a function are required by default. The parameters of a function should match the type specified by the function signature as well.

For Example:

function fullName(first:string, middle:string, last:string)
{
  return first+" "+middle+" "+last;
}

fullName("Mark");//Error parameters middle and last are missing

fullName("Mark", null,null);//Error: null is not assignable to string

fullName("Mark", undefined,undefined);//Error: undefined is not assignable to string

Syntax for optional parameters

Here is the code that declares middle and last names to be optional:

function fullName(first:string, middle?:string, last?:string)
{
  return first+" "+middle+" "+last;
}

fullName("Mark");//No Error
//Prints Mark undefined undefined

However, there is a problem; fullName("Mark") will print out

Mark undefined undefined

Try this code in typescript playground

This is because we are not checking the contents of middle and last parameters.

That shows one important point about optional parameters. You have to check whether the parameters are present or not. Let’s do that first.

How to check if optional parameter was passed

You can check the type of the parameter . If the parameter is undefined, then the optional parameter is not passed. For example:

function fullName(first:string, middle?:string, last?:string)
{
  if( typeof middle == "undefined")
    {
        middle = ""
    }
    if( typeof last == "undefined" )
    {
        last = ""
    }
  return (first+" "+middle+" "+last).trim();
}  

In this case, however any falsy value can be treated the same way. So the code can be simplified like so:

function fullName(first:string, middle?:string, last?:string)
{
    middle = middle || "";
    last = last || "";
    return (first+" "+middle+" "+last).trim();
}

fullName("Mark");//No Error

fullName("Mark", undefined, undefined);//No Error

fullName("Mark", undefined,"Bennet");//No Error

The code above checks the value of the parameters for falsy values (that includes undefined, null and empty string as well) and initializes to empty string.

Try this code in typescript playground

Default Parameters

In the case of the fullName() function, we can simplify the code by making use of default parameters. Like so:

function fullName(first:string, middle:string ="", last:string="")
{
  return (first+" "+middle+" "+last).trim();
}  

The default value is made to be empty string

Try this code in typescript playground

How to skip the optional parameter

You can pass undefined as a parameter if you just want to skip one parameter. Like so:

fullName("Mark", undefined,"Bennet")