Reputation: 25280
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.
Upvotes: 0
Views: 71
Reputation: 37996
Parameter initializer can be empty object:
function test({ a = true, b = false }: { a?: boolean, b?: boolean } = {}) {
console.log(a, b);
}
Upvotes: 2