To transform initial data into functional data, each with its own type, I need to address the optional names in the initial data. When converting to working data, I assign a default value of '__unknown__'
for empty names.
Check out this code snippet:
/* @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
}
In the above example, initializing working1
is successful, but trying to initialize working2
using the object spread operator triggers a flowtype error:
4: name?: string
^ undefined. This type is incompatible with
8: name: string
^ string
I'm puzzled by how the spread operator can cause this issue. Any insights on this would be appreciated. Thank you.
Check out the "Working" example on https://flowtype.org/try/...
here.