Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 20007

Flow believes value is null even after wrapping in an if statement

this.collapsible is a React Ref with type ?HTMLElement. I'm trying to set a style like so:

this.collapsible.style.height = ...

And, despite wrapping the above in an if (this.collapsible && this.collapsible.style), it seems that flow still believes that this.collapsible.style could be null.

Cannot get this.collapsible.style because property style is missing in null or undefined [1].

      97│
      98│   componentDidMount() {
      99│     if (this.collapsible && this.collapsible.style) {
     100│       this.collapsible.style.height = getInitialHeight(this.props);{
        :
 [1] 148│   collapsible: ?HTMLElement;

How can this be resolved?

Upvotes: 2

Views: 47

Answers (1)

Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 20007

As @John Ruddell pointed out, aliasing a variable works.

if (this.collapsible) {
  const collapsible: HTMLElement = this.collapsible;
  collapsible.style.height = getInitialHeight(this.props);

I wasn't able to find a nice way to cast the type without having to create a new variable.

Upvotes: 1

Related Questions