Flow: Providing Flow typing for function argument when using default object values

Created on 19 Jul 2018  路  2Comments  路  Source: facebook/flow

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.

Most helpful comment

Your problem can be reduced to a simpler example鈥攚ith intersection
types, optional and non-optional properties don鈥檛 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.

All 2 comments

Your problem can be reduced to a simpler example鈥攚ith intersection
types, optional and non-optional properties don鈥檛 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.

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

Was this page helpful?
0 / 5 - 0 ratings