Skip to content

Typecasting Object assignment within Array.forEach #377

@SergioRevueltas

Description

@SergioRevueltas

Hi,

This might be a silly question but...

I need to reset some Object values and I decided to use a forEach loop. This Object values are defined as it follows:

image

Basically, I've declared this Object type. It's important the Object contains at least 2 attributes with different types. For example, a number and a string:

type FooType = {|
  a: number,
  b: string
|}

And I have written an Object of the same type that will be used to set/reset the initial values in another one of the same type.

const INITIAL_FOO: FooType = {
  a: 0,
  b: ''
}
const foo: FooType = {
  a: 1,
  b: 'qwerty'
}

Therefore, when I use the Array.forEach for an assignment I get the following flow error:

Object.keys(foo).forEach((key) => {
  foo[key] = (INITIAL_FOO[key]: any); // This works
})
Object.keys(foo).forEach((key) => {
  foo[key] = INITIAL_FOO[key];        // This fails
})
18:   foo[key] = INITIAL_FOO[key];        // This fails
                 ^ Cannot assign `INITIAL_FOO[key]` to `foo[key]` because number [1] is incompatible with string [2]. [incompatible-type]
References:
3:   a: number,
        ^ [1]
4:   b: string        ^ [2]
18:   foo[key] = INITIAL_FOO[key];        // This fails
                 ^ Cannot assign `INITIAL_FOO[key]` to `foo[key]` because string [1] is incompatible with number [2]. [incompatible-type]
References:
4:   b: string        ^ [1]
3:   a: number,
        ^ [2]

I guess that Flow is not able to detect that the key used to read from INITIAL_FOO and the key used to write in foo are the same on every loop.

Is there any way to fix this and keep the forEach loop?

Here is a link to test this example: https://flow.org/try

Thanks,

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions