Optional typed immediately destructured parameters?

Presumably you’re unhappy about the following error:

const fooBad = ({ bar }?: { bar?: boolean }) => {}; // error!
// ┌──────────> ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
// A binding pattern parameter cannot be optional in an implementation signature.

Which makes sense, because you can’t destructure undefined. What you can do, in TypeScript, is to use a default function parameter. This is treated like an optional parameter from the calling side of the function (so you can leave it out), and on the implementation side it sets a value of the parameter if it is undefined.

So, what do you want to destructure if someone calls foo()? I’m guessing you want bar to be undefined, right? So that would mean you either pass in something like {bar: undefined}, or (since bar is optional), the empty object {}:

const foo = ({ bar }: { bar?: boolean } = {}) => {
  console.log(bar);
};

I’ve added console.log(bar) so you can see what it becomes when you call it:

foo(); // undefined
foo({}); // undefined
foo({bar: true}); // true

Looks good to me. Hope that helps; good luck!

Link to code

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)