首页 > 解决方案 > 解构 Flow 对象类型?

问题描述

我正在为 Apollo 客户端生成流类型,我目前有这个:

type FetchModuleQuery = {|
  // Fetch single module
  module: ?{|
    // ID
    id: string,
    // Name
    name: string,
    // Fetch list of assignments for module
    assignments: ?Array<?{|
      // Created date
      createdAt: any,
      // ID
      id: string,
      // Name
      name: string
    |}>
  |}
|};

但是,此数据位于我的父组件<Component1 />中,我像这样渲染它的子组件:

<Component2 assignments={this.props.module.assignments} />

这很好用;我正在做所有我需要做的检查以保持 Flow 快乐。但是,我想不出最干净的方式来输入 my <Component2 />; 理想情况下,我想使用这个现有的FetchModuleQuery对象类型,而不是创建任何新的东西。

有任何想法吗?

标签: javascriptreactjsgraphqlflowtypereact-apollo

解决方案


您可以使用类似于导入和导出真实模块的语法来导入和导出流类型。对于您的情况,您可以提取assignments为另一种类型并执行以下操作:

组件1.js

export type FetchModuleQueryAssignments = ?Array<?{|
  // Created date
  createdAt: any,
  // ID
  id: string,
  // Name
  name: string
|}>;

export type FetchModuleQuery = {|
  ...,
  assignments: FetchModuleQueryAssignments,
|};

组件2.js

import type { FetchModuleQueryAssignments } from './Component1';

推荐阅读