-
Notifications
You must be signed in to change notification settings - Fork 1.9k
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
Problem with object spread syntax where the object type has optional values #6751
Comments
Here's a workaround: foo({ ...null, foo: 'foo', ...a }); |
Thank you so much for this, you've saved me from having to put a heinous |
Seems like it might be a bug with the type refinement process, it's like the type is being refined too early and then being compared against. When doing: type A = { foo: ?string };
const a: A = { foo: 'foo' };
const bar = { foo: 'foo', ...a }; The type of Spreading any You can even spread the same object twice to prevent the type refinement: foo({ ...a, foo: 'foo', ...a }); |
Looking further this might actually be intentional and expected. Consider that the following: type A = { foo: ?string };
# The following are equivalent
const x = { foo: 'foo', ...a };
const x = Object.assign({ foo: 'foo' }, a); Which means the inferred type of the first argument in the When using spread syntax you're actually creating an object, which has its type inferred (because you haven't defined it) and then you're trying to assign an incompatible type object over it. When really it sounds like the intention is: const x = Object.assign({}, { foo: 'foo' }, a);
# or the same as
const x = Object.assign(null, { foo: 'foo' }, a); I can't think of what possible bug this error is protecting us from, but I think it is technically correct in its implementation. So the solution of first merging |
Made a PR to fix this: #7298 |
This code no longer errors in master |
Example at Try Flow
The following code:
Produces this error:
It also produces an error if I define the type as:
In that case I get:
The text was updated successfully, but these errors were encountered: