通过条件

时间:2018-06-16 21:16:19

标签: javascript flowtype

说我有以下类型:

type MyCustomAction = {|
  type: "MY_CUSTOM_ACTION",
  payload: string
|}

type MyCustomAction2 = {|
  type: "MY_CUSTOM_ACTION2",
  data: number
|}

type CustomAction = MyCustomAction2 | MyCustomAction


const MyCustomFunction = (action: CustomAction): void => {
  const type = action.type

  if (type === "MY_CUSTOM_ACTION") {
    let payload = action.payload
  } else if (type === "MY_CUSTOM_ACTION2") {
    let data = action.data
  }
}

这失败了:

21:         let payload = action.payload                                 ^ Cannot get `action.payload` because property `payload` is missing in `MyCustomAction2` [1].
References:
17:     const MyCustomFunction = (action: CustomAction): void => {
                                          ^ [1]
23:         let data = action.data                              ^ Cannot get `action.data` because property `data` is missing in `MyCustomAction` [1].
References:
17:     const MyCustomFunction = (action: CustomAction): void => {
                                          ^ [1]

尝试流程的链接:https://flow.org/try/#0FDAuE8AcFMAIFlwGECuBnUB7AtgQQMagCWmAdrALywDeAPsLLBDAFywBE8AmgPpICqAZQAqAeXg9cSYQElRAOXYAaBrEgBDcABtM6gCZsMAJyKkA5sFoBfVYzBQ4iVBhwFiZAEyUa9Rn-8BgUEBzNBsnLwCIuKS0nLyHsq2wSmpjHrqoOpspCjYAEbQRslppQHWycmhsM5YeIQk5FRO6HVujV6+AS0u9e6kIMn4ZBgIyK04AGIopA1k3gAU6nOkbLWuKwCUbABumER6lAB8NCWww6Sj1VTL-QB0oSCBRABmsAvXFFQRfEJiElJZAp2JtTsEtNBQGpNDp9N5bo07hptLo9GcrLBoFo0HBXu9Pt9uL9ogC4gpEqDqGdGBCoRksvCVnd6ep0ckbMAgA

是否可以切换这样的类型?为什么流不能检测到MyCustomAction总是有一个有效载荷?

1 个答案:

答案 0 :(得分:0)

似乎在流编译器中是一个问题,但是如果直接使用对象字段,它会很好:)

type MyCustomAction = {|
  type: "MY_CUSTOM_ACTION",
  payload: string
|}

type MyCustomAction2 = {|
  type: "MY_CUSTOM_ACTION2",
  data: number
|}

type CustomAction = MyCustomAction2 | MyCustomAction

const MyCustomFunction = (action: CustomAction): void => {
    if (action.type === 'MY_CUSTOM_ACTION') {
        const payload = action.payload;
    } else if (action.type === 'MY_CUSTOM_ACTION2') {
        const data = action.data;
    }
};

Try