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.
When destructuring object parameters in a function, separate the destructured parameters and the type for the specific properties with a colon, e.g. function getPerson({ name, age }: { name: string; age: number }) {} . Copied!
In Typescript, “?” represents optional parameters. We use optional parameters when it's not mandatory for that parameter to have a value or to be specified. Even if a function specifies parameters, you can call it without giving any arguments in JavaScript.
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
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