Reputation: 770
I'm playing around with TS and encountered an error when trying to run a test for my code. I have a the following piece of code:
return this._map.get(y)?.get(x)
When I run the code for browser, everything works fine. When I run a test using mocha
, however, it throws an error :
return this._map.get(y)?.get(x);
^
SyntaxError: Unexpected token .
From what I managed to read, I'm supposed to configure tsc
differently for NodeJS environment for things to work, but I was under the impression it was more about module resolution than syntax. Could it be that I need to upgrade to any specific NodeJS version? I've tried Node 10 through 13 but none worked.
What am I missing?
Upvotes: 5
Views: 10235
Reputation: 7730
Optional chaining was added in ES2020, which isn't supported by Node yet. So if your target compile option is ES2020 or ESNext, then TypeScript compiler will see an optional chaining operator and leave it alone.
If your target is ES2019 or further back then typescript will transpile the feature into something that Node will understand. something like:
const attributeScores = (_a = apiResponse === null || apiResponse === void 0 ? void 0 ...
Source : Syntax Error with Optional Chaining in Typescript 3.7
Upvotes: 0
Reputation: 12860
I was able to resolve this in Node 12 with TypeScript by changing my tsconfig.json:
"compilerOptions": {
"lib": ["ES2019"],
"module": "es2015",
"target": "ES2019",
...
}
I was getting this error when my target
was "esnext"
. After I changed to "ES2019"
it worked just fine in Node 12. Hope that helps.
Upvotes: 3
Reputation: 1074355
Optional chaining is still behind a flag in Node.js v13. It isn't anymore in the latest Node.js (v14.9.0), though it still was in v14.4.0, so it got deflagged somewhere between those two.
Either update to the latest, or to enable it in v13 and earlier versions of v14:
node --harmony-optional-chaining ...
Upvotes: 8