javascript - 流量: Inference error in for-of loop

标签 javascript flowtype

我有一个代码试图验证具有指定类型的属性id和_name的对象。属性id应该是一个数字,name应该是一个在FooT类型中声明的字符串。

function number(value: mixed): number {
  if (typeof value === "number") return value
  throw new TypeError("number required")
}

function string(value: mixed): string {
  if (typeof value === "string") return value
  throw new TypeError("string required")
}

function objectOf(attrs, value) {
  const obj = {}
  for (const key of Object.keys(attrs)) {
    const typeFn = attrs[key]
    obj[key] = typeFn(value[key])
  }
  return obj
}

type FooT = {
  id: number,
  name: string
}

const fooT: FooT = objectOf(
  {
    id: number,
    name: string
  },
  {
    id: 1,
    name: "Foo"
  }
)

运行流程显示此错误。由于某种原因,动态访问对象属性值时,在 for-of 循环中无法正确确定 typeFn 的推断返回类型。

Cannot assign objectOf(...) to fooT because:
 • string [1] is incompatible with number [2] in property id.
 • number [3] is incompatible with string [4] in property name.

 [3]  3│ function number(value: mixed): number {
       :
 [1]  8│ function string(value: mixed): string {
       :
 [2] 22│   id: number,
 [4] 23│   name: string
     24│ }
     25│
     26│ const fooT: FooT = objectOf(
     27│   {
     28│     id: number,
     29│     name: string
     30│   },
     31│   {
     32│     id: 1,
     33│     name: "Foo"
     34│   }
     35│ )
     36│

这是流量问题还是我遗漏了什么?

最佳答案

您似乎遇到了issue #935 Type of object value not inferred correctly in for-in loop 。您应该能够使用suppress_comment配置并只需将 $FlowFixMe 放入代码中即可告诉 Flow 忽略它。

关于javascript - 流量: Inference error in for-of loop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48857465/

相关文章:

javascript - 仅在启用时如何设置选择框的值?

对象属性链上的 Flowtype "Not covered by Flow"

javascript - 流: check type of thenable

reactjs - 无法将流类型设置为 react 状态

javascript - 是否可以绑定(bind)一个javascript函数,使其本地上下文与 'this'相同?

javascript - 在 javascript 中使用 fetch 时访问 header

javascript - 参数之前或之后的流类型问号?

reactjs - ESLint 报告流类型全局类型的 no-undef 错误

javascript - 您如何开发跨浏览器兼容性?

javascript - 取消(重置 html)按钮不起作用