Skip to main content

模块类型

导入和导出类型

¥Importing and exporting types

在模块(文件)之间共享类型通常很有用。在 Flow 中,你可以从一个文件导出类型别名、接口和类,然后将其导入到另一个文件中。

¥It is often useful to share types between modules (files). In Flow, you can export type aliases, interfaces, and classes from one file and import them in another.

exports.js

1export default class MyClass {};2export type MyObject = { /* ... */ };3export interface MyInterface { /* ... */ };

imports.js

import type MyClass, {MyObject, MyInterface} from './exports';

不要忘记在文件顶部添加 @flow,否则 Flow 将不会报告错误。

¥Don't forget to add @flow at the top of your file, otherwise Flow won't report errors.

将值导入和导出为类型

¥Importing and exporting values as types

Flow 还支持导入其他模块使用 typeof 导出的值的类型。

¥Flow also supports importing the type of values exported by other modules using typeof.

exports.js

1const myNumber = 42;2export default myNumber;3export class MyClass { /* ... */ };

imports.js

import typeof MyNumber from './exports';
import typeof {MyClass} from './exports';

const x: MyNumber = 1; // Works: like using `number`

就像其他类型导入一样,编译器可以删除此代码,这样它就不会添加对其他模块的运行时依赖。

¥Just like other type imports, this code can be stripped away by a compiler so that it does not add a runtime dependency on the other module.