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

1.2k views Asked by At

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
2

There are 2 answers

1
brunnerh On

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);

0
Awais On

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');