FlowType:类型的继承(类型A是类型B的子集...)

juk*_*ben 13 javascript flowtype

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

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

我们假设我有这种类型

type A = {
 x: number
}

type B = {
 y: string
}
Run Code Online (Sandbox Code Playgroud)

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

type C = {
 ...A,
 ...B,
 z: boolean
}
Run Code Online (Sandbox Code Playgroud)

恕我直言应该被解释为:

type C = {
  x: number,
  y: string,
  z: boolean
}
Run Code Online (Sandbox Code Playgroud)

但这显然不起作用.

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

Nat*_*ote 14

这是一个常见的功能请求,它实际上正在进行中.这是一个实现解析类型扩展的提交.我不确定这个功能的时间表是什么,但我相信它仍然在进行中.

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

type C = A & B & {
  z: boolean
}
Run Code Online (Sandbox Code Playgroud)

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


kro*_*oss 5

我已经证实传播正如你所期望的那样工作,十字路口让我到处都是。这是一个简短的操场,展示了流型交集未能使道具可选,而传播有效

后代的示例代码:

// @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
Run Code Online (Sandbox Code Playgroud)