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

Providing Flow typing for function argument when using default object values #6616

Closed
jmarceli opened this issue Jul 19, 2018 · 2 comments
Closed

Comments

@jmarceli
Copy link

I'm not sure but I think that this might be a Flow bug. I'm unable to add Flow typing when using Object.assign to provide default values for function arguments. Here is a SO question: https://stackoverflow.com/questions/51422411/flow-default-values-type-checking/51431098

And here is a direct link to reproduce this problem on flow.org/try: https://flow.org/try...

Any help will be appreciated.

@wchargin
Copy link
Contributor

Your problem can be reduced to a simpler example—with intersection
types, optional and non-optional properties don’t mix well:

// @flow
type ConfigIn = {someValue?: number};
type Config = ConfigIn & {someValue: number};
const c: Config = {someValue: 1000};  // error!

(Potentially related: #5929.)

Using the type-spread operator (...) instead fixes this, and fixes
the downstream problem in your example
:

// @flow
type ConfigIn = {someValue?: number};
type Config = {...ConfigIn, someValue: number};

function test(config: ConfigIn): number {
  const myConfig: Config = Object.assign(
    {},
    {someValue: 1000},
    config
  );
  return otherFunction(myConfig.someValue);
}

function otherFunction(input: number): number {
  return 123;
}

Frankly, intersection types seem to break more often than they work.
I avoid them altogether.

@jmarceli
Copy link
Author

jmarceli commented Jul 20, 2018

Thanks, this is it.

What is more, for anyone interested, it is sometimes good to use Exact object types to avoid nested properties problem example and solution

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

2 participants