如何导出从另一个文件导入的流类型定义

How do you export a Flow type definition that is imported from another file?

本文关键字:类型 定义 导入 文件 何导出 另一个      更新时间:2023-09-26

给定从另一个模块导入的类型定义,如何重新导出它?

/**
 * @flow
 */
import type * as ExampleType from './ExampleType';
...
// What is the syntax for exporting the type?
// export { ExampleType };

这个问题最简单的形式是"如何导出类型别名",简单的答案是"使用export type !"

例如,你可以写

/**
 * @flow
 */
import type * as ExampleType from './ExampleType';
export type { ExampleType };

你可能会问"为什么ExampleType是一个类型别名?"当你写

type MyTypeAlias = number;

您正在显式地创建别名MyTypeAlias,别名number。当你写

import type { YourTypeAlias } from './YourModule';

您正在隐式地创建类型别名YourTypeAlias,它别名YourModule.jsYourTypeAlias导出。

下面的代码运行得很好

export type { Type } from './types';

接受的答案是旧的,并在我这端抛出警告。考虑到视图的数量,这里有一个与流0.10+兼容的更新答案。

MyTypes.js:

  export type UserID = number;
  export type User = {
    id: UserID,
    firstName: string,
    lastName: string
  };

User.js:

  import type {UserID, User} from "MyTypes";
  function getUserID(user: User): UserID {
    return user.id;
  }

我在@locropulenton的答案上找到了一个需要的一行代码来为ES6默认类做这个。假设你有

// @flow
export default class Restaurants {}

Restaurants.js文件中。要从同一目录下的index.js文件导出它,请执行以下操作:

export type {default as Restaurants} from './Restaurants';