【问题标题】:Refine on optional property in union type with flow使用流优化联合类型中的可选属性
【发布时间】:2018-07-09 18:27:13
【问题描述】:

我有一个联合类型Entity,由两种不同的类型组成,DoorHandle。属性旋转存在于其中一种子类型中,但不存在于其他子类型中。这似乎意味着我无法优化该属性,但得到错误Cannot get entity.rotation because property rotation is missing inHandle[1].

我知道它不见了,所以我试图检查它是否在那里。

type Door = {
  id: number,
  rotation: number
}

type Handle = {
  id: number
}

type Entity = Handle | Door;

const foo = (entity: Entity): number => {
  if (entity.rotation) {
    return entity.rotation;
  } else {
   return 2;
  }
}

无法获取entity.rotation,因为Handle 1 中缺少属性rotation

有没有办法细化属性在类型中存在或不存在的位置?

Running example in the flow editor

【问题讨论】:

  • 仅供参考,您可以检查 rotation 是否为 number: if (typeof entity.rotation === 'number')

标签: javascript flowtype


【解决方案1】:

通过不将 Handle 声明为严格类型,您是在告诉 Flow 它可能包含旋转属性。

type Door = {
  id: number,
  rotation: number
}

type Handle = {|
  id: number
|}

type Entity = Handle | Door;

const foo = (entity: Entity): number => {
  if (entity.rotation) {
    return entity.rotation;
  } else {
   return 2;
  }
}

Flow editor

Flow documentation link

【讨论】:

  • 是的,但我正在检查该属性是否存在。我想知道的是,如果属性存在于类型中,是否有办法细化
  • 您正在检查属性是否存在于不严格的对象上,这是一个有效的声明:const _handle: Handle = { id: 42, rotation: 2}; 来自文档的引用对于确切的对象类型,我们不能有其他属性,因此对象冲突彼此之间,我们能够区分哪个是哪个。
  • 所以我只能检查类型是否严格的属性?
  • @stinaq,不,您可以检查非严格对象的属性。但是,如果您尝试改进不相交联合的类型,则您需要跨对象类型的共享属性(可能是更好的方法),或者您需要使用 sanghin 的答案中的确切对象
猜你喜欢
  • 1970-01-01
  • 2019-05-13
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多