【问题标题】:[flow]Multiple type check[流程]多种类型检查
【发布时间】:2017-05-06 12:23:06
【问题描述】:

我用flowType写express router代码,让flow检查req.body数据,body数据有多种类型,如UserData(bbb type)或LoginData(ccc type)。但是当身体将数据转换为功能时,流程总是说错了。有没有什么好主意来支持 body 有多种类型检查?这是一个演示错误代码。

/* @flow */

declare type ccc = {
  ccc: string;
}

declare type bbb = {
  bbb: string;
}

declare type aaa = {
  body: bbb | ccc
}

function test(aaa: aaa) {
  const body = aaa.body

  test2(body)
}

function test2(body: ccc): string {
  return body['ccc']
}

【问题讨论】:

  • 如果您编辑问题以包含完整的错误文本,那么有人会更容易快速帮助您。

标签: javascript flowtype flow-typed


【解决方案1】:

错误

这是使用flow 运行提供的代码时遇到的错误:

 34:   test2(body)
       ^^^^^^^^^^^ function call
 37: function test2(body: ccc): string {
                          ^^^ property `ccc`. Property not found in
 34:   test2(body)
             ^^^^ object type

解决方案

这里的主要问题是test2aaabody 值可以是 bbbccc 类型,这意味着当您调用

const body = aaa.body

  test2(body)

body 可以匹配bbb 类型或ccc 类型,我们不知道。同时,test2 明确地只接受ccc 类型的参数。 Flow 看到了 bbb 类型被传递的可能性,当然,它没有 ccc 属性。至少一种解决方案是进行以下更改:

function test2(body: bbb | ccc): string {
  if (typeof body.ccc === 'string') {
    return body.ccc
  }

  return ''
}

我们需要bbb | ccc,因为它实际上可以是任一种选择。接下来,我们需要typeof 检查以确保在我们传入bbb 类型的情况下不返回undefined。这消除了错误。

【讨论】:

    猜你喜欢
    • 2021-11-24
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 2017-07-07
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多