Miguel
Miguel

Reputation: 1636

Typescript: Object is possibly null event after an if in React

I'm writing a react application using Typescript and in my render method I have this error:

Object is possibly null

The thing is that I am already checking if the object is not null. Here is my code:

interface State {
  tutorial: any;
}

export default class Tutorial extends PureComponent<any, State> {
  state = {
    tutorial: null,
  };

  componentDidMount() {
    loadTutorial(this.props.match.params.id).then((res: any) => {
      this.setState({ tutorial: res.tutorial });
    });
  }

  render() {
    if (this.state.tutorial === null) return null;

    return (
      <section>
        <h1>Tutorial: {this.state.tutorial.title}</h1>;
      </section>
    );
  }
}

But I still have the error in the render method. How can I solve it?

Upvotes: 1

Views: 1412

Answers (1)

Aaron Beall
Aaron Beall

Reputation: 52133

Odd error. It seems to have to do with the fact that you don't have a type annotation where you initialize state, and you set tutorial to null:

state = {
  tutorial: null,
};

In other words, TypeScript thinks the type of state is literally { tutorial: null } so you can't narrow away null. However I'd expect it to narrow to never which is why I find the error message odd.

Change that to this:

state: Readonly<State> = {
  tutorial: null,
};

And your code works. (Enable strictNullChecks to validate.)

Even though React type definitions say state: Readonly<S> I've found that to get the correct behavior you often have to explicitly annotate the state property, else TypeScript will infer the type from the initialization value and that might not be the same as the S type arg passed to the component.

Upvotes: 3

Related Questions