【问题标题】:Need clarification about flowtype "exact Union Types"需要澄清流类型“确切的联合类型”
【发布时间】:2018-03-12 17:59:06
【问题描述】:

我不明白工会是如何运作的。

文档参考

看到这个doc example关于exact Union Types

问题

下面的代码将在item.rocks 上引发流错误:

/* @flow */

type MoutainType = {|
  rocks: boolean,
|};

type OceanType = {|
  waves: boolean,
|};

type HolidayType = MoutainType | OceanType;


const haveHoliday = (item: HolidayType) => {
  return item.rocks; //----------------> Error (but shouldn't)
}

自己试试

See live demo

【问题讨论】:

  • 您当前的设置意味着它可以是任何一种类型,但其中只有一个具有rocks 属性。流错误,因为它告诉您该属性并不总是有效。是否期望 HolidayType 成为具有 both 的对象?如果是这样,也许你想要flow.org/en/docs/types/intersections,而不是联合。

标签: flowtype


【解决方案1】:

您已将HolidayType 定义为MountainTypeHolidayType 类型的联合。 Flow 需要能够确定它正在处理的类型,然后才能允许您访问独占成员属性而不会引发错误。

如果您在尝试访问 rocks 属性之前对其进行测试,Flow 将能够确定正在使用的类型。

const haveHoliday = (item: HolidayType) => {
  if (typeof item.rocks !== 'undefined') {
      // Flow now knows that this must be a MountainType
      return item.rocks;
  }
}

查看Disjoint Unions 的文档,看看是否有可以用作类型选择器的字面值,这会为您提供更自然的代码路径,例如

type MountainType = {
  terrain: 'rocks'
}

type OceanType = {
  terrain: 'waves'
}

type HolidayType = MountainType | OceanType

const haveHoliday = (item: HolidayType): boolean => {
  return item.terrain === 'rocks'
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    • 2015-10-23
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多