Search code examples
javascriptreact-nativeflowtype

Flow clearTimeout is incompatible with TimeoutID


I am working on a React Native App, that I require to use Flow.

I am still getting around the entire concepts of let arr: Array<React$Element<Component>> = []

But there is somethings that for as much as I research I cannot figure out how to define the type of the variable that I will use to clearTimeout.

using what this guy said: 0.63.x regression: setTimeout() & setInterval() return types broken

he says to use:

const foo: TimeoutID = setTimeout(() => {}, 300);
const bar: IntervalID = setInterval(() => {}, 300);

but eventually I have to make a clearTimeout() and I get:

Cannot call clearTimeout with this.playerTimeOut bound to timeoutId because null or undefined (see line 17) is incompatible with TimeoutID (see https://github.com/facebook/flow/blob/v0.78.0/lib/core.js#L733).

Code:

playerTimeOut: ?TimeoutID = null;

componentDidMount() {
  const { children } = this.props;
  const { index } = this.state;

  this.playerTimeOut = setTimeout(() => {
    clearTimeout(this.playerTimeOut);

    this.setState({
      index: index >= this.total ? 0 : index + 1
    });
  }, parseInt(children[index].attr.runningtime) * 1000);
}

Really appreciate any help or constructive improvements :D


Solution

  • Not sure what the magic you're implementing, but would notice that timeout will be cleared right first run, so you don't need to explicitly call the clearTimeout.

    However, if you're sure you need this, what flow see is:

    playerTimeOut: ?TimeoutID = null;
    

    so, it might be null or undefined.

    To fix this either:

    a) define without maybe type:

    playerTimeOut: TimeoutID; // no question mark, no default value.
    

    Try

    b) refine maybe type using if condition:

    if(this.playerTimeOut) {
       clearTimeout(this.playerTimeOut);
    }