How can one tell if a JS function returns undefined or null?


#1

I was looking at the definition of Js.String.get in bucklescript/jscomp/others/js_string.ml, which gives this signature:

external get : t -> int -> t = "" [@@bs.get_index]

This code: Js.log(Js.String.get("abc", 4)) prints out undefined. A discussion in discord indicates that the signature is incorrect, and should be:

external get : t -> int -> t option = "" [@@bs.get_index][@@bs.return {undefined_to_opt}]

However, given the original signature: is there a way to find out in generic Reason code if a value returned from a JavaScript external function is null or undefined? Or should it be handled in the external signature by specifying nullable?


#2

Js.Nullable.test can inform be used to check whether a given value is null or undefined. This is a bit of a hack though. It means that the type definition is not sound. Ideally the external signature should specify nullable.


#3

You’ll need to examine the original JS function or prop to understand whether it could be null or undefined. If it could, you’ll need to reflect that appropriately in the binding. Sometimes you can’t tell exactly, in which case it’s better to be on the safe side and return a nullable type. Of course sometimes it’s possible to make a mistake in writing the binding and that can lead to unsoundness, but we hope to avoid or fix that as much as possible.


#4

If it doesn’t show it in the signature then it’s wrongly written


#5

Then it would seem that the signature for get is incorrect; @splodingsocks filed an issue / PR: https://github.com/BuckleScript/bucklescript/pull/2712