【问题标题】:Destructure a Flow object type?解构 Flow 对象类型?
【发布时间】:2018-12-16 05:47:24
【问题描述】:

我正在为 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
    |}>
  |}
|};

然而,这个数据位于我的父组件&lt;Component1 /&gt;,我渲染它的子组件是这样的:

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

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

有什么想法吗?

【问题讨论】:

  • 在打字稿中你可以做FetchModuleQuery["module"]["assignments"],不知道等效流程

标签: javascript reactjs graphql flowtype react-apollo


【解决方案1】:

IMO 最简洁的方法是提取“帮助”类型并使用它,就像在 Ross Allen 的回答中一样。

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

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

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

【讨论】:

    【解决方案2】:

    您可以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';
    

    【讨论】:

    • 是的,我明白;但是,我特别想获得FetchModuleQuery 对象类型的assignments 部分,可能作为单独的对象类型。这可能吗?
    • @think123 哦,好吧,我误会了。是的,您可以将其提取到另一种类型并导出该类型。我更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2017-02-02
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2022-10-23
    • 1970-01-01
    相关资源
    最近更新 更多