Combining object destructuring with flow-typing
Asked Answered
N

2

8

I just added Flow to my Create-React-App project, and while converting some of my calculation code to flow-typed, I encountered this error with a destructured "object as params"

Original sig:

calcWeightOnConveyor({ tonsPerHour, conveyorLength, conveyorSpeed })

After flow-type:

calcWeightOnConveyor({ tonsPerHour: number, conveyorLength: number, conveyorSpeed: number }): number

And the error:

$ flow
Error: src/utils/vortex/calculate.js:31
 31: export function calcWeightOnConveyor({ tonsPerHour: number, conveyorLength: number, conveyorSpeed: number }) {
                                                                                 ^^^^^^ Strict mode function may not have duplicate parameter names

Is there a way to use flow with object destructuring in this way or should I redesign these function APIs?

Nullity answered 12/1, 2018 at 18:3 Comment(3)
When you use colons in destructuring, the right side of the colon is actually creating a new variable. You are creating two variables named "number". Check out the MDN docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Stylize
Flow type collides with ES6 here.Huxham
github.com/facebook/flow/issues/235Huxham
L
7

Generally the pattern I follow, especially for functional components props is as follows:

type Props = {
  prop: Type,
};

const Component = ({
  prop,
}: Props) => ();
Legra answered 12/1, 2018 at 18:33 Comment(2)
github link is 404 btwNullity
oops :| removed since I think we have that repo private for now.Legra
S
5

Yes you can do so by annotating the entire object like the following:

calcWeightOnConveyor({
  tonsPerHour,
  conveyorLength,
  conveyorSpeed
}: {
  tonsPerHour:number,
  conveyorLength:number,
  conveyorSpeed:number
}):number
Stylize answered 12/1, 2018 at 18:9 Comment(1)
Probably the best answer until flow/ts address this with either as or paren-style { (tonsPerHour:number) } as referenced in @jonas-w comments above.Nullity

© 2022 - 2024 — McMap. All rights reserved.