Null safety in javascript


I’ve started writing multi-platform modules and pretty quickly have started noticing some inconsistencies between JVM and JS and as such wanted to get a better understanding of what I should be doing.

For example, given the following sample code:

class Upper(id: String) {
    val upper: String = id.toUpperCase()

JavaScript compiles this to:

function Upper(id) {
    this.upper = id.toUpperCase();

String is supposed to be non-null and the JVM compiler adds in Intrinsics.checkParameterIsNotNull(id, “id”); to enforce this.

However, as the JavaScript version lacks this check calling the function with a null value will result in an exception when toUpperCase is called, generally a TypeError. In more complex code this exception might be outside of the constructor, but ultimately in an unpredictable location.

As a potential solution I was thinking to add in checkNotNull(id) however there are still differences in implementation, in Java you get an IllegalArgumentException and in Javascript an IllegalStateException.

The question I have, is there a better solution or indeed will null checks be added by the javascript compiler at some point?


Adding those checks would most likely destroy performance and significantly increase the compiled JS size. So it’s a tradeoff I guess.

If you absolutely need this, you could write those checks manually. Inline functions could make life a bit easier, but it would still be a pain. =(

If you think this is an important feature, you could file a proposal here and explain your use case.