【问题标题】:Object with same type for all keys in FlowFlow 中所有键的类型相同的对象
【发布时间】:2016-12-15 23:04:58
【问题描述】:

我目前正在比较 Google Closure CompilerFlow 静态类型检查器的表现力。我知道如何在 Closure 中但在 Flow 中不知道的一件事是表达一组具有相同类型的命名对象。在闭包中可以使用the @enum annotation

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

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

【问题讨论】:

    标签: javascript dictionary types flowtype


    【解决方案1】:

    你可以这样做:

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

    如果不想重复key,可以稍微重写一下:

    const unaryFunctions_ = {
      sin: Math.sin,
      cos: Math.cos,
      square: function(x) { return x*x; },
    };
    
    const unaryFunctions: { [$Keys<typeof unaryFunctions_>]: (number) => number } = unaryFunctions_;
    

    【讨论】:

    • 谢谢!您可以添加一些文档链接吗?我找到了$Keys,但没有找到有关您使用[…] 的方式的文档。另一方面,我找到了indexer properties,如果我理解正确,它应该允许const unaryFunctions: {[name: string]: (number) =&gt; number} = {…}。不限于一组有限的键,所以它不完全是@enum,但我知道我需要这样的另一种情况。还是您的[…] 是这种情况的一个实例?
    • flowtype.org/docs/objects.html#objects-as-maps 您在括号内指定密钥类型。它可以是字符串或任何更具体的内容
    • 在较新版本的 Flow 中,您可以在索引器中省略名称,因此您可以简单地编写 {[string]: string} 而不是 {[name: string]: string}
    • 现在加上引号,以及关于不命名索引器的信息,这更有意义。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-19
    相关资源
    最近更新 更多