Search code examples
f#funscript

FunScript querySelector null result


I want to use document.querySelector method to get html node. In Js I can receive null as a result. But in F# the result type is Element and it's neither nullable nor optional and it's not clear how to check it for null. How can I handle the situation when querySelector doesn't match any DOM node?


Solution

  • Yes, it's true the F# code assumes Element is not nullable. You can trick the compiler to think otherwise in several ways. Probably the easiest one is to box the value like this:

    let el = Globals.document.querySelector(".myclass")
    if (box el) = null
    then doSomething()
    else doSomethingElse()`
    

    box will be ignored when generating the JS code, so there's no performance penalty in doing this.