我希望将初始数据转换为工作数据。两者都有自己的类型,唯一的区别是在初始数据中,名称是可选的。在创建工作数据时,我对空名称使用默认值'__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
我不明白扩散运算符怎么会导致这种情况。有人能解释一下吗?谢谢。
https://stackoverflow.com/questions/41257357
复制相似问题