Object with same type for all keys in Flow

1.2k views Asked by At

I'm currently in the process of comparing the Google Closure Compiler and the Flow static type checker, in terms of expressiveness. One thing I know how to do in Closure but not in Flow is expressing a collection of named objects which all have the same type. In Closure one can use the @enum annotation for this.

/** @enum {function(number):number} */
const unaryFunctions = {
  sin: Math.sin,
  cos: Math.cos,
  square: function(x) { return x*x; },
};

Is there a way to do something like this using Flow? I guess I could use an ES6 dictionary instead of a plain object, but that would come at considerable overhead if cross-compiling to ES5. I think constructs like these seem pretty idiomatic, so I'm surprised I couldn't find a matching type description in the docs yet.

1

There are 1 answers

4
vkurchatkin On BEST ANSWER

You can do it like this:

const unaryFunctions: { ['sin'|'cos'|'square']: (number) => number } = {
  sin: Math.sin,
  cos: Math.cos,
  square: function(x) { return x*x; },
};

If you don't want to duplicate keys, you can rewrite it a bit:

const unaryFunctions_ = {
  sin: Math.sin,
  cos: Math.cos,
  square: function(x) { return x*x; },
};

const unaryFunctions: { [$Keys<typeof unaryFunctions_>]: (number) => number } = unaryFunctions_;