代码之家  ›  专栏  ›  技术社区  ›  Laurent S

如何使用流量型es6发电机

  •  0
  • Laurent S  · 技术社区  · 6 年前

    我正在尝试定义 mystring gen 保存 flow 很高兴,但我找到的唯一解决办法是 string|void mystring string 这是意料之中的事,不是吗 void

    我应该如何修改此代码以修复错误?

    // @flow
    import * as React from 'react';
    
    type State = {
        mystring: string|void,
    };
    
    type genType = Generator<string, void, void>;
    
    export default class Example extends React.Component<{}, State> {
        constructor(props: {}) {
            super(props);
            this.gen = this.makeGenerator();
            const { value } = this.gen.next();
            this.state = {
                mystring: value,
            };
        }
    
        gen: genType;
    
        * makeGenerator(): genType {
            yield 'somestring';
        }
    
        render() {
            const { mystring } = this.state;
            return mystring.charAt(0);
        }
    }
    

    在上面的代码中,最后一行(这是一个迫使flow思考的示例) 作为字符串):

    Cannot call mystring.charAt because property charAt is missing in undefined [1].
     [1]  5│     mystring?: string,
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Jesse Hallett    6 年前

    用于将类型参数引用到 Generator 像这样:

    interface Generator<+Yield,+Return,-Next>
    

    next() 您将获得此类型的结果:

    type IteratorResult<+Yield,+Return> =
      | { done: true, +value?: Return }
      | { done: false, +value: Yield };
    

    done: true 案例流假设 value 结果中可能缺少属性。这意味着,无论您如何键入生成器,Flow都假定 价值 可能是 void done: false 案例流将使用您指定的任何类型作为 Yield 发电机的类型。因此,您可以检查 done 提炼 价值

    const result = this.gen.next();
    if (!result.done) {
      this.state = {
          mystring: result.value,
      };
    }
    

    支票 !result.done result { done: false, +value: Yield } string 价值 ,不可能 无效的

    通过该更改,您可以更新要删除的状态类型 来自的类型联合 mystring :

    type State = {
        mystring: string,
    };
    

    发电机 IteratorResult 以上来自Flow的标准类型定义,您可以在此处看到:

    https://github.com/facebook/flow/blob/master/lib/core.js