我有一个代码试图验证具有指定类型的属性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/