1

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?

1
  • Do you use strict null checks? Commented Jan 11, 2019 at 16:53

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is the correct answer. As a further insight, the issue is that without the annotation the state is inferred as { tutorial: null }. This means tutorial will always be null, regardless of the check. The correct error would be "unreachable code", but I think the type error takes the precedence here.
you can reproduce the same error with const x = { a: null }; if (x.a != null) { x.a.hey; }
Thank you! Explicitly setting state to Readonly<State> or :State solves the issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.