Default Parameters in TypeScript

The Default Parameters option was added in the ES6 version of JavaScript. In this tutorial let us learn What is Default Parameters and how to use them in TypeScript

Default Parameters

The default parameters allow us to initialize the parameter with default values if no value or undefined is passed as the argument.

The following is the syntax for providing the default value in TypeScript.

The code below uses the default value for the parameter c. Note that we call addNum without a value for the parameter c. The code initializes the parameter c with 0 and returns 3.

The above code without the default value for c will result in a compiler error. This is because we have supplied value for only 2 parameters while the function expects 3.

Multiple Default Parameters

A function can have multiple default parameters.

Using Expressions as Default Values

You can use also use any expression as a default value. In the example below b takes an expression.

Evaluated at call time

The JavaScript evaluates the parameters and updates the default values when we call the function.

In the following example, the a is 1 and b becomes 3 when we call addNum for the first time. We change the value of x & y and when we call the addNum again it will evaluate default values again. Hence a is 5 and b becomes 10.

Using earlier Parameters

You can also make use of earlier parameters in the default value expressions.

In the code below, b uses a in its expression.

Passing undefined

You can not pass undefined if we use default values. Because, If the value is undefined then TypeScript assigns the default value.

Hence if you want to pass an undefined value, then do not use default values

Default Parameters can appear anywhere

The default Parameters can appear anywhere in the parameter list.

In the following example, the first two parameters have default values. But the third parameter c does not have one. Here if we want to pass a value to the parameter c, then we need to explicitly pass undefined to a & b.

Function as default Value

You can also use another function as the Default Value.

The showNumber uses another function getNumber to assign a default value to the parameter a

Making Parameter Optional

We can make the parameter optional using the ?. But that would result in NaN

To solve this, we need to check if the c is undefined. If it is then initialize it with 0.

Reference

  1. Manual

Read More

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top