Error when using the spread operator in objects with an additional property

I want to turn raw data into operational data. Both have their own type, the only difference is that in the source data the names are optional. When I create working data, I use the default value '__unknown__'for empty names.

Here is a sample code:

/* @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
}

At the end of the above example, initialization working1is fine, but initialization working2using the object's distribution operator causes flowtype to show this error:

4:  name?: string
            ^ undefined. This type is incompatible with
8:  name: string
           ^ string

I do not understand how the distribution operator can do this. Can someone explain this? Thank.

"Working example" on https://flowtype.org/try/...here .

+4
1

. .

, , , 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

.

+1

Source: https://habr.com/ru/post/1664391/


All Articles