Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flow : destructuring. Missing annotation in React/Preact

Just getting started with Flow but can't seem to understand what it wants me to do with adding types for destructuring objects like i.e. props

i.e.

render({ count }, { displayHelp }) {

Throws an error like

 16:   render({ count }, { displayHelp }) {
              ^^^^^^^^^ destructuring. Missing annotation

and when I add annotation it still complains

 17:   render({ count: number }, { displayHelp }) {
              ^^^^^^^^^^^^^^^^^ destructuring. Missing annotation

I am obviously missing something very simple here if anybody could point out ?

like image 303
StevieB Avatar asked Apr 10 '17 16:04

StevieB


People also ask

What is destructuring assignment in react?

How to avoid repetition and keep your code clean with destructuring assignment in React Destructuring assignment is a feature of JavaScript introduced by ES6 (or ES 2015) that’s available for both object and array data types.

When to destruct an array in react?

When destructuring arrays, the order that variables are declared is important. If we only want the car and suv we can simply leave out the truck but keep the comma: Destructuring comes in handy when a function returns an array: Get Certified! Complete the React modules, do the exercises, take the exam and become w3schools certified!!

What is the usestate hook from react destructuring?

In fact, the useState hook from React returns an array with two values that we destructure immediately. Here’s an illustration of how it works: The benefits of using destructuring assignment is especially visible when using React because you would deal with state and props frequently.

How to pass props from one component to another in react?

First, destructure the userData props before passing it to the component: Then pass it into the component as two props: Or you can also use spread operator so you don’t need to destructure it: Then immediately destructure the props object when you define the parameters in the function, like this:


1 Answers

The problem with doing { count: number } is that this clashes with ES6 syntax for destructuring assignment, where you can use { a: b } = c in order to take the value with key a from c and have it be named b, ie:

const c = { a: 1 }
const { a: b } = c
//b is now a constant with value 1

There isn't really a good workaround for this in Flow right now, but this seems to work (although it is ugly):

render({...}: { count: number }, { displayHelp }) {

The best way right now seems to be to create a custom type which captures your props:

type propsForThisComponent = {
  propA: someType
  propB: anotherType
  ...
}

and then do:

render(props: propsForThisComponent) {

This typechecks, although it forces you to access all your props as props.propName.

like image 102
Pedro Castilho Avatar answered Sep 28 '22 01:09

Pedro Castilho