12

Suppose I have a function as below

function addressCombo(street1:string, street2:string = "NA", street3?:string) {
    console.log("street1: " + street1);
    console.log("street1: " + street2);
    console.log("street2: " + street3);
}

And I want to pass values for parameter street1 and street3 but not street2 then how can I do that?

I am from C# background and we do it as below

addressCombo("ABC", street3 : "XYZ");
norbitrial
  • 14,716
  • 7
  • 32
  • 59
Imad
  • 7,126
  • 12
  • 55
  • 112
  • 1
    I wish it worked more like C#, it seems weird that you can make a function have an optional parameter but you still have to pass it an undefined value for each optional parameter anyway. – Brendan Sluke Mar 12 '21 at 15:48

2 Answers2

13

This is not really a TypeScript question but a JavaScript question.

Optional parameters must be at the back and can only be left out if all later arguments are left out as well. Otherwise JavaScript doesn't know for which parameter you passed a value.

Consider the second parameter in your example is optional. In a call you would just leave it out and not pass a value.

function addressCombo(street1, street2, street3) {}

addressCombo("LA", "LO")

However JavaScript doesn't know that you intended "LO" to be the argument for street3 and not street2. Instead it will assign them in the row.

In other words, you can't have an argument for street3 after you left out street2.

What you could to is explicitly pass undefined to the optional parameters, which is what would happen anyway if you left an argument out. In your example this would be

addressCombo("LA", undefined, "LO")

Please see also

Skip arguments in a JavaScript function

javascript: optional first argument in function

How to pass optional parameters while omitting some other optional parameters?

mdcq
  • 1,593
  • 13
  • 30
  • 1
    Both the answers work for me, but I think the accepted one is more flexible. If the number of such parameters grows passing `undefined` will be hard and a bit ugly. +1 though. – Imad Mar 29 '20 at 12:40
6

You could use an object to pass your parameters (or something like streets: { [key: string]: string }):

function addressCombo(streets: { street1?: string; street2?: string; street3?: string }) {
  console.log("street1: " + streets.street1);
  console.log("street2: " + streets.street2);
  console.log("street3: " + streets.street3);
}

addressCombo({ street1: 'A', street2: 'B', street3: 'C' });
// Log:
// street1: A
// street2: B
// street3: C

addressCombo({ street1: 'A', street3: 'C' });
// Log:
// street1: A
// street2: undefined
// street3: C
pzaenger
  • 11,381
  • 3
  • 45
  • 46