Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typecasting Object assignment within Array.forEach #377

Open
SergioRevueltas opened this issue Mar 15, 2022 · 0 comments
Open

Typecasting Object assignment within Array.forEach #377

SergioRevueltas opened this issue Mar 15, 2022 · 0 comments

Comments

@SergioRevueltas
Copy link

SergioRevueltas commented Mar 15, 2022

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,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant