Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flow types on objects

I've been looking at adding Flow to my javascript project.

In several cases, I do something like this, I have an object.

const myObject = {
    x: 12,
    y: "Hello World"
}

And I have a general function that does some mapping on the object, keeping the keys but replacing the values.

function enfunctionate(someObject) {
   return _.mapValues(myObject, (value) => () => value)
}

I'd like the function to return the type {x: () => number, y: () => string} Is there a way to make this happen?

Of course, I could type it more generically as {[key: string]: any} but I'd lose a lot of the static typing I'd like to gain by using flow.

If I could replace my few cases that do this with code generation or macros that could work, but I don't see a good way to do that with flow.

Is there a way to solve this problem?

like image 914
Winston Ewert Avatar asked Sep 18 '16 00:09

Winston Ewert


People also ask

What are flow types?

Flow is a static type checker that allows a developer to check for type errors while developing code. This means a developer receives faster feedback about the code, which they can use to improve its quality. Flow works by using annotations and type definitions for adding type checking support to your code.

What is Flow object?

1 Definition. A graphical object that can be connected to or from a Sequence Flow. In a Process, Flow Objects are Events, Activities, and Gateways. In a Choreography, Flow Objects are Events, Choreography Activities, and Gateways.

What are the options considered as flow objects?

Flow objects can be separated into three. They are events, activities, and gateways.

What is mixed type flow?

Definition of mixed-flow : combining or utilizing in succession two or more different types of flow (as axial and radial) —used especially of turbines and pumps.


1 Answers

This is the best you can get at the moment, while it's safer than {[key: string]: any} there's still an any involved

function enfunctionate<O: Object>(someObject: O): { [key: $Keys<O>]: (...rest: Array<void>) => any } {
   return _.mapValues(someObject, (value) => () => value)
}

const obj = enfunctionate(myObject)

obj.x() // ok
obj.unknown() // error

EDIT: starting from v.33 you can use $ObjMap

function enfunctionate<O>(o: O): $ObjMap<O, <V>(v : V) => () => V> {
  return _.mapValues(o, (value) => () => value)
}
like image 53
gcanti Avatar answered Sep 28 '22 12:09

gcanti