解构 Flow 对象类型?

Destructure a Flow object type?

我正在为 Apollo Client 生成 Flow 类型,我目前有这个:

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 开心。但是,我想不出最干净的方式来输入 <Component2 />;理想情况下,我想使用现有的 FetchModuleQuery 对象类型,而不创建任何新对象。

有什么想法吗?

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

Component1.js:

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

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

Component2.js:

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

IMO 最干净的方法是提取 "helper" 类型并使用它,就像 Ross Allen 的回答一样。

或者,您可以使用 $PropertyType 实用程序类型。

type Component2Props = {
  assignments: $PropertyType<$PropertyType<FetchModuleQuery, 'module'>, 'assignments'>
}

这与评论中 Jonas W. 建议的 TypeScript 的 FetchModuleQuery["module"]["assignments"] 基本相同。