Optional Parameters in TypeScript

Optional Parameters in TypeScript are used when passing a value to a parameter of a function is optional. In this tutorial, we will learn what is Optional parameters, how to create a function with optional parameters. Will also learn the effect of strict null checks on optional parameter

Need for Optional Parameters

JavaScript functions allow us the pass an arbitrary number of arguments to a function. It does not throw any errors. For example, the following is a perfectly valid code in JavaScript.

The above code in TypeScript results in a Compiler error

There are two issues here

  1. Passing fewer arguments than the number of parameters
  2. Passing more arguments than the number of parameters

We use the optional parameters to solve the first issue and the rest parameters for the second use case

Optional Parameters

Optional Parameters in TypeScript are used when passing a value to a parameter of a function is optional. We do that by appending a ? after the parameter name.

In the following example, c is optional as we have appended ? after it.

If we do not pass any value to an optional parameter, then its value is set to undefined. That is why we need to check the value of an optional parameter before using it. TypeScript compiler also throws the error Object is possibly 'undefined' if we use it before checking for undefined.

We must declare the optional parameters after the required parameters in the parameter list. The optional parameter before the required parameter will result in an error. In the following example, we made b Optional instead of c. The compiler throws A required parameter cannot follow an optional parameter error.

Strict Null Checks

If Settings of Strict Null Checks is set to true, then TypeScript converts the type of optional parameter to a union type.

For example, in the following code data type of c becomes number | undefined. Because of this, the following code throws an error

But if we set Strict Null Checks is set to false, the type of c stays as a number. Due to this, the above code will not throw any error

Optional Parameters Vs Undefined

Instead of an optional parameter, we can assign a union type with undefined to the optional parameter. In the following example, the optional parameter of c is of type number. Hence we create a union-type of number | undefined.

This works very similarly to optional parameters except for the fact that we cannot omit the parameter. We need to supply undefined in case of no value.

On the other hand, we can make the parameter in any position undefined. While optional parameters must appear after the required parameters.

References

  1. TypeScript Handbook

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