If you aren't familiar with the new TypeScript "nullish coalescing operator" (??
), it's documented here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#nullish-coalescing
You can think of this feature - the ?? operator - as a way to “fall back” to a default value when dealing with
null
orundefined
.
I've just used this for the first time in some code, and I noticed something odd about the way the operator is translated into JavaScript. Using the TypeScript Playground, you can see that this code:
const message: string = process.env.FOO ?? 'bar';
Is translated into this:
"use strict";
var _a;
const message = (_a = process.env.FOO, (_a !== null && _a !== void 0 ? _a : 'bar'));
Since ??
tests for null or undefined values, why compare to void 0
instead of undefined
? I can't think of anything other than perhaps void 0
is just a few characters shorter than undefined
. Is there a better reason than that?