Flow中所有键具有相同类型的对象

时间:2016-12-15 13:24:35

标签: javascript dictionary types flowtype

我目前正在比较Google Closure CompilerFlow静态类型检查器的表现力。我知道如何处理Closure而不是Flow中的一件事是表达一组命名对象,它们都具有相同的类型。在Closure中,可以使用the @enum annotation来实现此目的。

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

有没有办法使用Flow做这样的事情?我想我可以使用ES6字典而不是普通对象,但如果交叉编译到ES5,那将会产生相当大的开销。我认为像这样的结构看起来非常惯用,所以我很惊讶我还没有在文档中找到匹配的类型描述。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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

如果您不想复制密钥,可以稍微重写一下:

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

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