Why this warning occurs?

Related code:

@bs.val external document: 't = "document"

React.useEffect0(() => {
    let handleClick = event => {
      setCount(_count => event["pageX"])
    }
    document["addEventListener"]("click", handleClick)

    Some(
      () => {
        document["removeEventListener"]("click", handleClick)
      },
    )
  })

The warning:

    setCount(_count => event["pageX"])
 }
 document["addEventListener"]("click", handleClick)

 Some(

    this statement never returns (or has an unsound type.)

The editor highlight:

Might be worth being a little bit more specific with your types here… i tried to replicate your example in a way how I would approach it:

module ClickEvent = {
  type t = { pageX: int } 
}

module Document = {
  type t
  
  @bs.val external document: t = "document"

  @bs.send
  external addEventListener: (t, string, ClickEvent.t => unit) => unit =
    "addEventListener"
  
  @bs.send external removeEventListener: (t, string, ClickEvent.t => unit) => unit = "removeEventListener"
}

let make = () => {
  let (count, setCount) = React.useState(_ => 0)
  React.useEffect0(() => {
    let handleClick = event => {
      setCount(_count => event.ClickEvent.pageX)
    }

    Document.document->Document.addEventListener("click", handleClick)

    Some(
      () => {
        open Document
        document->removeEventListener("click", handleClick);
      },
    )
  })
  
  <div>
  	{Belt.Int.toString(count)->React.string}
  </div>
}

Playground Link

1 Like

What if you do,

ignore(document["removeEventListener"]("click", handleClick))

(Not tested, just an idea)

Thanks, it clears the warning.

I found the doc on the Reason site (couldn’t find it on the Rescript site), and here’s the snippet for anyone else who might be interested:

let ignore: 'a => unit;
Discard the value of its argument and return (). For instance, ignore(f x) discards the result of the side-effecting function f. It is equivalent to f x; (), except that the latter may generate a compiler warning; writing ignore(f x) instead avoids the warning.

Thanks for your answer!

I would love to be more specific about my types and add more bindings. I just want to try out the quick prototyping approach which the official doc suggests.

Anyway, adding a ignore clears out the warning, thanks to @jacobp100, although I am still not clear why it appears.

I think it appears because the compiler cannot infer what the call to document["removeEventListener"]("click", handleClick) returns - and it wants to check you’re not ignoring any return values

You can also annotate that it returns nothing by writing (document["addEventListener"]("click", handleClick): unit) - and that gets rid of the error too

1 Like

For posterity: note that ryyppy’s solution is a more proper one if you’re writing any reasonably long-lived code and not just a one-off script.

2 Likes