Typescript optional parameters | Typescript Tutorials

javascript Aug 10, 2019

Typescript Optional Parameters

In JavaScript, it is possible to call a function without supplying any arguments, even where the function specifies parameters. It is even possible in JavaScript to pass more arguments than the function requires.In TypeScript, the compiler checks each call and warns you if the arguments fail to match the required parameters in number or type.
Because arguments are thoroughly checked, you will need to annotate optional parameters to inform the compiler that it is acceptable for an argument to be omitted by the calling code. To make a parameter optional, suffix the identifier with a question mark which is an updated version of the getAverage function, which accepts either two or three arguments.

Optional parameters must be located after any required parameters in the parameter list. For example, the second parameter cannot be optional if the third parameter is required .

function getAverage(a: number, b: number, c?: number): string {
    let total = a;
    let count = 1;
    total += b;
    count++;
    if (typeof c !== 'undefined') {
    total += c;
    count++;
}
const average = total / count;
return 'The average is ' + average;
}
// 'The average is 5'
const result = getAverage(4, 6);

When you use an optional parameter, you must check the value to see if it has been initialized. The typeof check is the common pattern for this check. If you used the shorthand check of (b), you would find that empty string and numeric zeroes would be treated as if the variable was undefined. The longer expression if (typeof b === 'undefined') avoids this by thoroughly checking the type and value.

Neeraj Dana

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Angular, React, React-Native, Vue js, Machine Learning