nullish coalescing commit by Kingwl · Pull Request #32883 · microsoft/TypeScript (original) (raw)
@DanielRosenwasser I've added the tests, emit appears to work as expected keeping the ()
around the a ?? b
. So as to conform to the grammar requirement that:
??
cannot immediately contain, or be contained within, an&&
or||
operation.
Hope I didn't miss the point of the tests 😅
@rbuckton or @DanielRosenwasser
One thing I noticed was that emit is using the actual identifier in the down level version of ??
. So x ?? 0
becomes typeof x !== undefined && x !== null ? x : 0
.
But if x
comes from an import, because of the order in which the transformations are applied, we might get side effects on the access to x
:
//test2.ts let x = { y: 1, x: 0 } let v = 0; Object.defineProperty(x, "x", { get() { return v++; } }) export = x; //usage.ts import { x, y } from './test2' let xo = x ?? "NO" console.log(xo); let yo = y ?? "NO" console.log(yo);
This will output 2
and 1
because let xo = x ?? "NO"
becomes var xo = typeof test2_1.x !== "undefined" && test2_1.x !== null ? test2_1.x : "NO";
which will call the getter multiple times.
I would just use the approach babel uses, use a temporary variable always ex. Thoughts ?