我想将初始数据转换为工作数据。两者都有自己的类型,唯一的区别是在初始数据中,名称是可选的。当我创建工作数据时,我使用默认值'__unknown__'
作为空名称。
以下是示例代码:
/* @flow */
type NAME_OPTIONAL = {
name?: string
}
type NAME_MANDATORY = {
name: string
}
type INITIAL = {
source: string,
data: NAME_OPTIONAL[] // <-- Here the names are OPTIONAL.
}
type WORKING = {
source: string,
data: NAME_MANDATORY[] // <-- Here the name are MANDATORY.
}
// We have some initial data.
const initial: INITIAL = {
source: 'some.server.com',
data: [{ name: 'Adam' }, { name: undefined }]
}
// And we want to turn initial data into working data.
const workingData = initial.data.map((i) => {
return {
name: i.name || '__unknown__'
}
});
// This is OK:
const working1: WORKING = {
source: initial.source,
data: workingData
}
// This is NOT OK:
const working2: WORKING = {
...initial,
data: workingData
}
在上面的示例结尾处初始化working1
是正常的,但使用对象扩展运算符初始化working2
会导致flowtype显示此错误:
4: name?: string
^ undefined. This type is incompatible with
8: name: string
^ string
我不明白传播运营商如何导致这种情况。任何人都可以解释一下吗?谢谢。
答案 0 :(得分:1)
有a lot of bugs about the spread operator。您的案例似乎与this one相同。
除非用…
替换Object.assign
运算符,否则在修复它之前可能没有解决方案:
const working2: WORKING = Object.assign({}, initial, { data: workingData })
如果仍然无效,您可以在该行上方添加注释:
// $FlowIssue
const working2: WORKING = Object.assign({}, initial, { data: workingData })
或者:
// $FlowIssue
const working2: WORKING = {
...initial,
data: workingData
}
然后在.flowconfig
:
[options]
suppress_comment=.*\\$FlowIssue
这将抑制错误。