Skip to content
Related Articles

Related Articles

Provide the syntax for optional parameters in TypeScript

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 24 Feb, 2022
View Discussion
Improve Article
Save Article

In Typescript, “?” represents optional parameters. We use optional parameters when it’s not mandatory for that parameter to have a value or to be specified. Even if a function specifies parameters, you can call it without giving any arguments in JavaScript. As a result, the optional parameters are supported by default in JaveScript but it’s not the same case in typescript.

Every function call in TypeScript is checked by the compiler and an error is issued when The function specifies a different number of parameters than the number of arguments or when alternatively, the kinds of arguments do not match the types of function parameters. We use the “?” after the parameter name to make a function parameter optional. Just like rest parameters optional parameters must appear after the main or the required parameters or errors get produced.

Syntax: Following is the syntax of the optional parameter:

parameter_name ? : type

Example 1: Using optional parameters in function

Here is a simple example of a function to add two numbers. The num2 is considered optional. In the program, we make sure that num2 has some value passed in by checking if it’s not undefined. So there are two cases, one if we pass a value to the optional parameter or if only the required values have values associated with them. 

Javascript




// Function to add two numbers
function add(num1: number, num2?: number): number {
  if (typeof num2 !== "undefined") {
    return num1 + num2;
  }
  return num1;
}
 
// Function call
console.log(add(2, 3));
console.log(add(9));


Output:

5
9

Example 2: Optional parameters must appear after the required parameters

Optional parameters must come after the required parameters. In the below example we contradict the statement by specifying optional parameters before the main ones, typescript compiler raised an error saying “A required parameter cannot follow an optional parameter”.

Javascript




// Add function
function add(num1?: number, num2: number): number {
  if (typeof num2 !== "undefined") {
    return num1 + num2;
  }
  return num1;
}
 
// Function call
console.log(add(2, 3));
console.log(add(9));


 
 

Output: 

 

error TS1016: A required parameter cannot follow an optional parameter.
    function add(num1?: number, num2: number): number { .. }

 

Reference: https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!