1
votes

I am using Flow with React and I have a class that uses State and Props types like below:

type B = {x:number}

type State = {
  a: ?B
};

type Props = {}

class MyClass extends React.PureComponent<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = {
      a: null,
    };
  }
...
myFunction=()=>{

console.log(this.state.a.x)// Flow error here

}

}

The Flow error is: Cannot get this.state.a.x because property x is missing in undefined. What is the problem with my type definition? Why should I use 'Props' type definition in my constructor(props: Props) {} ?

1

1 Answers

2
votes

?B means that the a property the same as B | null | void. Since you can'd do null.x or undefined.x Flow is throwing a valid exception. To get your code to work you could for instance change

console.log(this.state.a.x);

to be

console.log(this.state.a ? this.state.a.x : null);

so that if a has not been set to a B value, it will log null.

Alternatively you could make the type a: B, but then you'd need to have a B value to put in the state as an initial value, and it sounds like you may not have that, since your example state sets a: null.