简体   繁体   中英

Optional defaults for optional argument

I want to set default values to an optional argument. In the original code, the function contains multiple arguments and is called like this, where options is an optional argument and can contain multiple optional parameters:

func(arg1, arg2, options)

For simplicity, I removed the first two arguments in the following example. I'm currently doing it like this:

function test({ a = true, b = false }: { a?: boolean, b?: boolean } = { a: true, b: false }) {
    console.log(a, b);
}

// Examples
test();                      // true, false (defaults)
test({ a: false });          // false, false
test({ b: true });           // true, true
test({ a: false, b: true }); // false, true

There is a lot of redundancy in the function header. I'm looking for a way to simplify the code and remove the redundancy .

Parameter initializer can be empty object:

function test({ a = true, b = false }: { a?: boolean, b?: boolean } = {}) {
    console.log(a, b);
}

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM