2.11 Function with optional and default parameters

TypeScript allow us to define functions with optional parameters or set a default value for parameters when a value is not provided.

Getting Ready

All you need to be able to use optional and default parameters is an installation of TypeScript 2.0 or higher.

How to do it…

You can flag a function parameter as optional by appending a question mark to the parameter name:

function sume(mandatory1: number,
              mandatory2: number,
              optional1?: number,
              optional2?: number) {
  let result = mandatory1 + mandatory2;

  if (typeof optional1 !== undefined) {
    result = result + optional1;

  if (typeof optional2 !== undefined) {
    result = result + optional2;

  return result;

How it works…

The name of the optimal function parameters must end with a question mark and be located at the end in the list of parameters passed to the function.
As we can observe in the preceding code snippet, we must check if the optional parameters have been passed to the function to avoid runtime errors.
The TypeScript compiler however will effectively prevent us from some errors via the usage of compilation errors:

sume(2);         // Error
sume(2, 2);      // OK
sume(2, 2, 2);   // OK
sume(2, 2, 2, 2);    // OK
sume(2, 2, 2, 2, 2); // Error

There’s more…

Sometimes we are forced to set a default value when one of the optional parameters is not provided:

function save(val: any, date?: Date) {
	if(date === undefined) {
		date = new Date();
	// ...

You can declare a default value or a function parameter using the assignment operator:

function save(val: any, date: Date = new Date()) {
	// ...

You can then invoke the function with or without the default parameter:

const myDate = new Date();
save({});         // OK
save({}, myDate); // OK

Source Code

Function with optional and default parameters

See also

Refer to the recipe about functions with rest parameters to learn how to implemented functions with an unknown number of arguments.

Shiv Kushwaha