3

I want to have a function definition which should contain both Optional and Rest Parameter. While invoking the function, am not getting desired output from the function. While invoking a function should I use some special keyword or something?

In the below function, the address is an optional parameter and names is a Rest Parameter. How can I invoke this function?

function Greet(age:number,address?:string,...names: string[]):void{
    console.log(age);
    console.log(address);
    console.log(names)
}

Greet(20,"Mathan","Maddy")

Here am passing parameters only to age and names. but the second value "Mathan" is getting considered for address in my function.

Mathan
  • 143
  • 2
  • 6
  • _"am not getting desired output from the function"_ What does this mean? What is the input you are providing it? Are you expecting the function to be able to accept `names` _without_ an `address`? If so, that's not going to work. – JLRishe Aug 27 '19 at 03:39
  • Yeah, that's my question. I had updated my question. Provided more clarity to it. – Mathan Aug 27 '19 at 03:45
  • Think of this from the perspective of the JavaScript engine: how is it supposed to know that the `"Mathan"` in `Greet(20,"Mathan","Maddy")` is supposed to be a name and the `"90 Fake Street"` in `Greet(20,"90 Fake Street","Maddy")` is supposed to be an address? In both cases, all it knows is that it's being passed a number and two strings. It's not possible to use an optional parameter and a rest parameter in the way you're trying to do. You need to rethink your approach. – JLRishe Aug 27 '19 at 06:13
  • See also: https://stackoverflow.com/questions/30734509/how-to-pass-optional-parameters-in-typescript-while-omitting-some-other-optional?rq=1 – JLRishe Aug 27 '19 at 06:18

1 Answers1

4

I don't really see any way you could do it other than explicitly specify undefined for the optional value:

Greet(20, undefined, 'Maddy')

There isn't a way to infer whether the second parameter is the optional one, or the start of the rest ones.

Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
  • Yeah, I tried this, in this case, the address will be having undefined. Instead, I don't want to have any value to it. – Mathan Aug 27 '19 at 03:53
  • 2
    If you don't pass any value, the value will also be `undefined`. Log the output if you call `Greet(20)`. That's what `undefined` means. – Evan Trimboli Aug 27 '19 at 03:57
  • 1
    @Mathan `undefined` is as close to "no value" that you could ever get. – JLRishe Aug 27 '19 at 04:03