Search code examples
typescript

Optional typed immediately destructured parameters?


How do I write optional typed immediately destructured parameters?

To give an example I want the following function to be callable without providing any parameter.

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

As it is now, TypeScript complains that a parameter is missing.


Solution

  • 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