【问题标题】:How do you define and import a class type in flow?您如何在流程中定义和导入类类型?
【发布时间】:2018-09-05 02:06:14
【问题描述】:

是否可以在一个文件中定义一个类类型,然后显式导入另一个文件?

例如:

types.js

export type MyType {
  id: number,
  name: string,
};

declare class MyOject {
  constructor(): MyObject;
  getStuff(param: number): MyType;
  ...
}

main.js

import type {MyObject, MyType} from './types.js'; // <- flow does now recognize MyObject
....

我希望能够像在 main.js 中一样导入它,但这违反了流程,因为它无法将 MyObject 识别为有效导入。

我尝试了几种不同的解决方案都没有成功:

  • declare class 更改为export class 会导致流错误
  • 将“types.js”移动到流库文件夹意味着我必须从流模块而不是文件本身导入它。这打破了此文件对流类型文件的依赖性。

有没有办法定义流类类型并从定义它的文件中显式导入它?

【问题讨论】:

    标签: javascript class ecmascript-6 flowtype


    【解决方案1】:

    你会想要使用declare export class:

    Types.js

    // @flow
    export type MyType = {
      id: number,
      name: string,
    }
    
    declare export class MyObject {
      constructor(): void;
    
      getStuff(param: number): MyType;
    }
    

    Main.js

    // @flow
    import {MyObject} from './types.js'
    import type { MyObject as MyObjectType, MyType } from './types.js'
    
    const newObj: MyObjectType = new MyObject()
    

    作为回购:https://github.com/jameskraus/flow-exporting-declared-class

    【讨论】:

      猜你喜欢
      • 2017-09-10
      • 2019-04-30
      • 1970-01-01
      • 1970-01-01
      • 2015-12-12
      • 2019-10-05
      • 1970-01-01
      • 2017-04-19
      • 2020-01-28
      相关资源
      最近更新 更多