0 votes
in TypeScript - JavaScript's Superset by
How does TypeScript support optional parameters in function as in JavaScript every parameter is optional for a function?

1 Answer

0 votes
by

Unlike JavaScript, the TypeScript compiler will throw an error if we try to invoke a function without providing the exact number and types of parameters as declared in its function signature. To overcome this problem, we can use optional parameters by using question mark sign ('?'). It means that the parameters which may or may not receive a value can be appended with a '?' to mark them optional.

function Demo(arg1: number, arg2? :number) {              

}So, arg1 is always required, and arg2 is an optional parameter.   

So, arg1 is always required, and arg2 is an optional parameter.

Note: Optional parameters must follow the required parameters. If we want to make arg1 optional, instead of arg2, then we need to change the order and arg1 must be put after arg2.

function Demo(arg2: number, arg1? :number) {  

}

Related questions

0 votes
asked Mar 23, 2021 in JavaScript by sharadyadav1986
0 votes
asked Mar 23, 2022 in TypeScript - JavaScript's Superset by sharadyadav1986
...