Omit passing of parameter

Asked

Viewed 422 times

4

I have the following method that contains the second declared parameter

post(path:string, body: Object = {}){
   ...
}

And here the call of the same with the omission of the second parameter

obj.post('/path/obj');

Based on this, I have the following doubts:

  • Why Typescript allows omitting the second parameter?
  • That’s because of the literal statement?

2 answers

6


Why Typescript allows omitting the second parameter?

Because the language creators thought it was better. There’s no other way to answer that question. The probable motivation for allowing this is that it simplifies function call syntax in most cases when it makes sense to have something like this. This mechanism is called optional arguments since although it has a parameter declared in the function signature it is not necessary to pass an argument to it since in most cases the value that would be passed is the same and it would be unnecessary to repeat it always.

Several languages accept this. The alternative to give this flexibility is to overload functions or have to create a function with a different name to accept without the argument because in these two cases the parameter would not be declared. Much more complicated.

The language documentation calls the optional parameter, which is an error, the parameter cannot be optional, only the argument, probably the writer does not understand What is the difference between parameter and argument?.

That’s because of the literal statement?

For the mechanism to work it is necessary that the parameter knows what would be the default value to be adopted in the absence of the explicitly passed argument. So the presence of the literal being assigned to the parameter is a way that allows this mechanism to work.

But it would be a mistake to think that only the literal allows the omission of the argument. If the type has a default value it can work, for example if the type null pain, then even without an assigned literal in it if nothing is passed null will be the default value.

There are limitations to how this can be used, for example you can only omit arguments from right to left, the first in this order that is not omitted can no longer omit any other.

The language has no named arguments like some others, which would give more flexibility. I do not know exactly but it is likely that it is because Javascript already has a mechanism that can simulate this and then it should be used, even to avoid certain ambiguities, although it has nothing to do with the philosophy of Typescript.

3

Why Voce is setting a default value for the second parameter.

body:Object={}

The variable body and kind Object with the default value defined as {}(an empty object) To make it mandatory simply remove the ={}, thus

post(path:string, body: Object){

Browser other questions tagged

You are not signed in. Login or sign up in order to post.