How do I make the second parameter optional and use deconstruction?
So far this works, but it's a bit ugly. Anything better?
const fn = (required, optional = {id: undefined, name: undefined}) => {
const {id, name} = optional
console.log(required, id, name)
}
fn('hello') // hello undefined undefined
fn('hello', {id: 'world'}) // hello world undefined
fn('hello', {name: 'world'}) // hello undefined world
I found this for typescript, Optional deconstruction function parameter , but I don't think I can apply the solution without TS.
The same approach as the typescript solution you found works in ES6 as well:
function fn(required, {id, name} = {}) {
console.log(required, id, name)
}
Use the destructuring expression as the target for the defaulted parameter, not optional. Also I've dropped the explicit property initialisation with undefined, just using an empty object as the default value works fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With