bvandercar
bvandercar

Reputation: 344

How to pass optional parameter that comes after another optional parameter that you don't wish to specify

I want to pass a parameter to override a deafult parameter that comes later in the function declaration than another default parameter that I want to let be default. Is this possible? Here's an example of what I want to do:

function f(a:string, b:number=1, c:string='FOO'){
     // do stuff
}

f('val for a', 'val for c') // want b to still be default of 1

Upvotes: 2

Views: 1779

Answers (2)

Awais
Awais

Reputation: 341

You can use undefined to get the default working. Here's the way you can accomplish this thing in a good stylistic way

function test(a:string, b:number=1, c:string='FOO') {
    //other stuff
}

let _ = undefined

test('val for a', _, 'val for c');

Upvotes: 2

brunnerh
brunnerh

Reputation: 184346

According to documentation you need to explicitly set b to undefined to get the default.

function test(a = 1, b = 2, c = 3) {
    console.log(a, b, c);
}

test(undefined, 42, undefined);

Upvotes: 5

Related Questions