TypeScript Optional Parameters

Summary: In this tutorial, you will learn how to define and use optional parameters in TypeScript functions.

In JavaScript, you can call a function without passing any arguments even though the function specifies parameters. Therefore, JavaScript supports optional parameters by default.

In TypeScript, the compiler checks every function call and issues an error in the following cases:

  • The number of arguments is different from the number of parameters specified in the function.
  • The argument types are not compatible with the function parameter types.

Because the compiler thoroughly checks the passed arguments, you need to annotate optional parameters to tell the compiler not to issue an error when you omit them.

To make a function parameter optional, you use the ? after the parameter name. For example:

function multiply(a: number, b: number, c?: number): number {
    if (typeof c !== 'undefined') {
        return a * b * c;
    }
    return a * b;
}

Try it

How it works:

  • First, use the ? after the c parameter.
  • Second, check if the argument is passed to the function by using the expression typeof c !== 'undefined'.

Note that if you use the expression if(c) to check if an argument is not initialized, you would find that the empty string or zero would be treated as undefined.

The following shows how to call the multiply function:

function multiply(a: number, b: number, c?: number): number {
  if (typeof c !== 'undefined') {
    return a * b * c;
  }
  return a * b;
}

let d = multiply(10,20,30);
console.log(d);

let e = multiply(10,20);
console.log(e);

Try it

6000
200

The optional parameters must appear after required parameters in the parameter list.

For example, if you make the b parameter optional, and c parameter required, the TypeScript compiler will issue an error:

function multiply(a: number, b?: number, c: number): number {
    if (typeof c !== 'undefined') {
        return a * b * c;
    }
    return a * b;
}

Error:

error TS1016: A required parameter cannot follow an optional parameter.

Summary #

  • Use the parameter?: type syntax to make a parameter optional.
  • Use the expression typeof(parameter) !== 'undefined' to check if the parameter has been initialized.

Quiz #

Quiz

TypeScript Optional Parameters

4 questions

Review the lesson learning objectives

Was this helpful?