fable-browser icon indicating copy to clipboard operation
fable-browser copied to clipboard

`getElementById` is unsafe

Open alex35mil opened this issue 3 years ago • 2 comments

Hi, I was trying out F# recently and encountered a runtime error when using getElementById due to the return type being HTMLElement but not option<HTMLElement>.

alex35mil avatar Jun 24 '22 08:06 alex35mil

Thanks for pointing this out. We had this discussion before (I forgot where so I don't have a link, sorry), but the conclusion was in general we're not using option to represent anything that can be null in JS. One of the reasons is that when we converted the fable-browser bindings from .d.ts declarations, Typescript wasn't "null safe" yet, so it was difficult to know which APIs could return null values without checking one by one. Maybe we could try to do it now but it may cause several breaking changes.

For now you can just do a null check as you would do in JS, either with isNull op pattern maching:

match document.getElementById "my-id" with
| null -> // do something
| el -> // do something else

alfonsogarciacaro avatar Jun 24 '22 14:06 alfonsogarciacaro

Once https://github.com/dotnet/fsharp/pull/15181 lands, we should be able to indicate nullability in bindings. Hopefully the latest compiler and lang version switch will be enough (both on the side of this repo and user projects).

kerams avatar May 26 '23 07:05 kerams