Optional Parameter in TypeScript

Abdu Manaz C A
Nerd For Tech
Published in
3 min readSep 9, 2021

--

What will be the output of the following code?

Will it throw an error, or will it execute?

It will execute and we will give the output- Printing: 1
Because,

In JavaScript, you can invoke a function with any number of arguments.

As we are aware, TypeScript brings compile-time type checking to JS.

If we change the language to TypeScript and then try to compile the file, we will get the following error:

So in TS, what if you want a function to be invoked primarily using 1 argument but it also should have the ability to accept a second argument?

Enter optional parameters.

Optional parameters allow us to mark inputs as optional so that even if the function is invoked without passing those values, it will still execute.

To mark a parameter as optional, put a ? after the parameter name.

So the above function becomes:

Now compilation is successful. But we still haven’t used the optional parameter in the code. To do that we have to check whether the optional parameter has any value.

To do that, we can use the typeof operator. If typeof operator returns ‘undefined’ (string undefined), it means the optional value is empty. So our code becomes:

Now when we execute the code, we will get the following output as expected:

And lastly, optional parameters should be declared after the required parameters. So in our example, if we put param2 as the first parameter of the function, then we will get the following error:

If you have found this article helpful, make sure to clap and share it with your friends. If you have any suggestions/comments let me know. And make sure to follow me so you don’t miss any articles.

--

--