Flow中的可迭代类 [英] Iterable class in Flow

查看:130
本文介绍了Flow中的可迭代类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Flow中定义可迭代类?

How to define iterable class in Flow?

以下代码(尝试流动):

// @flow

class A {
  [Symbol.iterator](): Iterator<string> {
    return {
      next() {
        return {
          done: true
        }
      }
    }
  }
}

报告错误

4:   [Symbol.iterator](): Iterator<string> {
     ^ computed property keys not supported

根据流问题流不喜欢将符号作为对象键例如在无法使用符号的情况下直接使用.

According to Flow issue Flow doesn't like Symbols as object keys it looks like direct use if symbols is not possible.

推荐答案

您必须使用一些解决方法,但是您可以定义一个可迭代的类.如果您查看Flow的内置定义,可以看到Flow在内部使用名为@@iterator的属性作为[Symbol.iterator]的替代.您需要做的是在类上同时定义两个属性:[Symbol.iterator]获取运行时迭代器功能,而@@iterator以便Flow知道用于类型检查的类迭代器功能.

You have to use some workarounds, but you can define an iterable class. If you look at Flow's built-in definitions you can see that Flow internally uses a property called @@iterator as a stand-in for [Symbol.iterator]. What you have to do is to define both properties on your class: [Symbol.iterator] to get runtime iterator functionality, and @@iterator so that Flow knows what the class iterator capability is for type-checking.

如前所述,如果尝试定义属性[Symbol.iterator],则Flow将引发错误.您可以使用// $FlowFixMe批注解决该问题:

As you noted Flow will throw an error if you try to define a property [Symbol.iterator]. You can get around that using a // $FlowFixMe annotation:

// $FlowFixMe
[Symbol.iterator](): Iterator<string> { /* ... */ }

另一方面,@@iterator在Flow之外不是有效的属性名称.例如,Babel将抛出语法错误.但是无论如何@@iterator都不需要在运行时存在,因此您可以在Flow注释中定义它,以便只有Flow可以看到它.放在一起,您将得到:

On the other hand @@iterator is not a valid property name outside of Flow. For example Babel will throw a syntax error. But @@iterator does not need to exist at runtime anyway, so you can define it in a Flow comment so that only Flow sees it. Putting this together you get:

export class A {
  // $FlowFixMe
  [Symbol.iterator](): Iterator<string> {
    return {
      next() {
        return {
          done: true
        }
      }
    }
  }

  /*::
  @@iterator(): Iterator<string> {
    // $FlowFixMe
    return this[Symbol.iterator]()
  }
  */
}

请注意该注释的特殊格式:它必须以精确的字符/*::开头,以使Flow可以将注释的内容解释为声明.

Note the special formatting of that comment: it must begin with exact characters /*:: to get Flow to interpret the content of the comment as a declaration.

这篇关于Flow中的可迭代类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆