facebook / flow

Adds static typing to JavaScript to improve developer productivity and code quality.
https://flow.org/
MIT License
22.09k stars 1.85k forks source link

Union Operator: Property not found in object type. #5817

Open matthewdordal opened 6 years ago

matthewdordal commented 6 years ago

Using React with Flow, I have a property on state that is initialized as an empty object {} and will have data after a promise resolves. I defined a type for the resolved data object. When I use the union operator to define the 2 possible values of the state I get a Property not found in object type error.

Here's a link to an example in flow try

Code example:

/* @flow */

type Data = {
    name: string,
}

type State = {
    data: Data | {} 
}

const state: State = {
    data: {}
}

const { data } = state
const { name = '' } = data // Property not found in object type

Is there a way for Flow to recognize that state.data.name is a possible value here even if the promise is not yet resolved? I'm not sure how to handle this case of a default state with an empty object.

idiostruct commented 6 years ago

state.data.name could be made optional.

matthewdordal commented 6 years ago

@idiostruct I had thought about using the optional property and that may be the way to go. In my case the type Data is modeled on an api response that would always have a name property. I had thought that the union operator could could work here. For modeling types on api responses I was hoping to avoid making every property optional, but maybe that is the right idea here.

idiostruct commented 6 years ago

Another option is to use$Shape<Data>: Try Flow.

matthewdordal commented 6 years ago

@idiostruct thank you! $Shape<Data> looks like it's exactly what I need. I searched the Flow docs but the only reference I found was it's use at the bottom of this page on casting.

Thanks!