Flow : destructuring. Missing annotation in React/Preact
Asked Answered
R

3

5

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 ?

Refine answered 10/4, 2017 at 16:19 Comment(0)
V
7

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.

Vitovitoria answered 10/4, 2017 at 16:28 Comment(3)
I just tried this and I get a syntax error. Are you sure that works?Spur
Nope, that was a mistake. It's actually a proposed feature. I'm looking for an actual way to get this to work right now and I'll edit as soon as I know a good one.Vitovitoria
Ok I gotcha, I should have spotted the ES6 conflict. Thanks for your help !Refine
S
2

You need to do something like this:

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

Unfortunately I do not believe there is a more concise way to do this.

Spur answered 10/4, 2017 at 16:29 Comment(0)
D
2

This works for me

type Props = {
    counter?: number
};

const Component = ({counter}: Props) => (
    <div className="App">
        {counter}
    </div>
);
Diamond answered 15/8, 2018 at 2:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.