TypeScript Tutorial
Tags

Typescript Optional Parameters

TypeScript is a strong typed language. When we declare parameters for a function then all the parameters are required and client has to pass values to every parameter. When client has no value for any parameter then he can pass null value. TypeScript provides a Optional parameters feature. By using Optional parameters featuers, we can declare some paramters in the function optional, so that client need not required to pass value to optional parameters.

Optional Parameter Syntax

We need to add a question mark "?" at the end of paramter name to mark this parameter optional. Below is the syntax.


function functionName(par1: number, par2?: number) {

}

In above syntax, par2 parameter is optional.

TypeScript Optional Parameters Example


function getSchool(name: string, address?: string, pinCode?: string): string {
    //...
}

var school = getSchool("Elementary");
var school2 = getSchool("Little Kid", "UK");  
var school3 = getSchool("Rose Tree School", "US", "99501")

In getSchool function, two parameters address and pin code are optional. In first function call, we are only passing school name. In section function class, we are only passing name and address and in third function class, we are passing all parameters.

Optional Parameter Ordering

Optional parameters always come last in the parameter list of function. We can not put optional parameter first and then required parameters in the function like shown below:


function getSchool(var1?: number, var2: string) { } //ERROR

TypeScript throw below error message when we put optional parameter first from required parameters.

A required parameter cannot follow an optional parameter.

Optional Parameter Check

In function, we can check whether client has passed the parameter value or not. If parameter value is not passed, then default value is 'undefined'. Below is the example:


function getSchool(name: string, address?: string, pinCode?: string): string {
    if (address == undefined) {
        console.log('address not defined');
    }
    if (pinCode == undefined) {
        console.log('pincode not defined');
    }
    //...
}