如何在流中定义和导入类类型?

时间:2018-03-26 20:05:15

标签: javascript class ecmascript-6 flowtype

是否可以在文件中定义类类型,该类型在另一个文件中明确导入?

例如:

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会导致流量错误
  • 移动&#39; types.js&#39;到流库文件夹意味着我将不得不从流模块而不是文件本身导入它。这会破坏此文件对流类型文件的依赖性。

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

1 个答案:

答案 0 :(得分: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