Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional typed immediately destructured parameters?

Tags:

typescript

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.

like image 603
user1283776 Avatar asked Jul 10 '19 11:07

user1283776


People also ask

How do you write Destructured parameters?

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!

What is optional parameter in typescript?

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.


1 Answers

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

like image 62
jcalz Avatar answered Feb 01 '23 14:02

jcalz