Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining object destructuring with flow-typing

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?

like image 538
typeoneerror Avatar asked Jan 12 '18 18:01

typeoneerror


People also ask

Is flow deprecated?

Effective May 5, 2020 the Dynamics 365 connector used for data integrations, flows, Azure Logic Apps, and canvas apps is officially deprecated.

Can you Destructure an object?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.

How do you Destructure an object in es6?

When destructuring the objects, we use keys as the name of the variable. The variable name must match the property (or keys) name of the object. If it does not match, then it receives an undefined value. This is how JavaScript knows which property of the object we want to assign.

Can we Destructure function in JavaScript?

JavaScript Object Destructuring is the syntax for extracting values from an object property and assigning them to a variable. The destructuring is also possible for JavaScript Arrays.


Video Answer


2 Answers

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

type Props = {
  prop: Type,
};

const Component = ({
  prop,
}: Props) => ();
like image 195
ru3sch Avatar answered Oct 09 '22 01:10

ru3sch


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

calcWeightOnConveyor({
  tonsPerHour,
  conveyorLength,
  conveyorSpeed
}: {
  tonsPerHour:number,
  conveyorLength:number,
  conveyorSpeed:number
}):number
like image 5
Ross Allen Avatar answered Oct 09 '22 02:10

Ross Allen