Search code examples
javascriptgoogle-closure-compilergoogle-closure

Type annotation for converting nullability


I would like to have a function that can remove the nullability of a value (throwing an exception if the value is actually null), but I can't seem to get the type annotations correct. My first attempt was:

/**
 * @param {?T} obj
 * @param {string} message
 * @return {!T}
 * @template T
 */
function checkNotNull(obj, message) {
  if (obj === null) {
    throw message;
  } else {
    return obj;
  }
}

This doesn't seem to work, though. If I use it like foo(checkNotNull(someVar)) (where foo() expects a non-nullable parameter), I still get the TYPE_MISMATCH error (basically saying that the parameter is still marked as nullable).

Is there a way to actually do this? Or do I need to keep typing in the manual null-checks followed by explicit type hints?


Solution

  • This isn't possible in the current implementations. There are several changes in planned to allow this but nothing immanent.