【问题标题】:FlowType: Inheritance of Types (Type A is a subset of type B ...)FlowType:类型的继承(类型 A 是类型 B 的子集......)
【发布时间】:2017-07-06 00:17:37
【问题描述】:

自从Flow 42 发布以来,您可以 使用对象类型传播。 type TypeB = { ...TypeA };????

我想这真的是关于 FlowType 的初学者类型的问题,但我真的找不到让我满意的答案。

假设我有这种类型

type A = {
 x: number
}

type B = {
 y: string
}

现在我想要基于类型 A 和 B 的另一种类型,如下所示:

type C = {
 ...A,
 ...B,
 z: boolean
}

恕我直言,应该解释为:

type C = {
  x: number,
  y: string,
  z: boolean
}

但这显然行不通。

您能给我一些建议或最佳实践吗?非常感谢。

【问题讨论】:

    标签: javascript flowtype


    【解决方案1】:

    这是一个常见的功能请求,它实际上已经在进行中。这是a commit,它实现了类型传播的解析。我不确定这个功能的时间表是什么,但我相信它仍在进行中。

    目前,您可以在某些情况下使用交集类型(尽管它们并不是真正针对此用例设计的,并且可能会导致令人困惑的问题):

    type C = A & B & {
      z: boolean
    }
    

    当然,您现在也可以选择复制属性。这绝对是最简单的事情,虽然我同意它有点难吃。

    【讨论】:

    • 非常感谢您的回答!很高兴知道。
    【解决方案2】:

    我已经验证了传播的工作方式与您预期的一样,十字路口让我到处都是。这是一个简短的playground that shows flow type intersection failing to make a prop optional, whereas spread works

    后人的示例代码:

    // @flow
    
    export type Affiliation = {
      id: string,
    }
    
    export type Address = {
      address1: string,
    }
    
    
    export type BaseContact = {
      id?: string,
      addresses: Array<Address>,
      affiliations?: Array<Affiliation>,
    }
    
    type C = BaseContact & {
      addresses: Array<Address>,
    }
    
    type CC = {
      ...BaseContact,
      addresses?: Array<Address>,
    }
    
    type CCI = BaseContact & {
      addresses?: Array<Address>,
    }
    
    
    class X {}
    
    const c: C = new X() // fails
    const cc: CC = new X() // fails
    const cci: CCI = new X() // works
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-09
      • 2017-12-28
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      相关资源
      最近更新 更多