Provide the syntax for optional parameters in TypeScript
In TypeScript, optional parameters allow you to specify that a function parameter may be omitted when calling the function. You denote optional parameters by adding a question mark (?
) after the parameter name in the function declaration.
Syntax:
function functionName(param1: type, param2?: type, param3?: type) {
// Function body
}
Parameters:
param1
is a required parameter.param2
andparam3
are optional parameters.
When calling the function, you can provide values only for the required parameters or include values for optional parameters as needed.
Using optional parameters in the function
Example 1: 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 is 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
Optional parameters must appear after the required parameters
Example 2: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 { .. }
Summary
- Optional Parameters Syntax:
- In TypeScript, use the
parameter?: type
syntax to declare optional parameters in a function. - Example:
function exampleFunction(param1: string, param2?: number) { /* function body */ }
- In TypeScript, use the
- Checking Initialization:
- To check if an optional parameter has been initialized within the function, use the expression
typeof(parameter) !== 'undefined'
. - This check ensures that the optional parameter has a value before using it in the function logic.
- To check if an optional parameter has been initialized within the function, use the expression
Reference: https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters