6

Just updated to Angular 10 from 9.0

Every use of Optional Chaining (https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining) in my code now results in its own instance of the following error

ERROR in ./src/app/app.component.ts 39:18
Module parse failed: Unexpected token (39:18)
File was processed with these loaders:
 * ./node_modules/@ngtools/webpack/src/index.js
You may need an additional loader to handle the result of these loaders.
|         this.title = 'my-app';
|         const x = this.GetObject();
>         let y = x?.myvar;
|     }

I confirm that this error ONLY occurs when targeting es2020 as per below from my tsconfig.base.json file, but is fine when targeting es2019

"target": "es2020",  //If set to es2019 then all OK
"module": "es2020",
"lib": [
   "es2018",  //Error also occurs if this set to es2020
    "dom"
  ],

I confirm this error occurs in fresh Angular 10 application when newly generated as below, and then change target to es2020 (so it is not my code!) Typescript version is 3.9.7

npm install -g @angular/cli
ng new my-app

I also note that in the release notes of es2020 that 'Optional Chaining' is now a new feature. This makes me suspicious that Typescript compilation of 'Optional Chaining' somehow is not marrying up with the new es2020 feature?

How do I use Optional-Chaining in es2020?

JimbobTheSailor
  • 1,441
  • 1
  • 12
  • 21
  • 1
    This happens _because_ TypeScript is behaving correctly, since option chaining is native in ES2020, it is not transformed by the compiler. @ngtools/wepack is subsequently parsing the code and doesn't understand the operator. Make sure that you don't have multiple versions of TypeScript installed by running `npm ls typescript` – Aluan Haddad Jul 24 '20 at 02:48
  • Thanks Aluan, Should I raise this issue with the TypeScript dev team? If so, do you know where I would do so? – JimbobTheSailor Jul 24 '20 at 04:48
  • No, what I'm trying to explain is that it's not a TypeScript issue. It's another tool, apparently @ngtools/webpack, that doesn't understand the new syntax. setting target to ES2020, means `?.` will not be transformed because it's part ECMAScript 2020. If you lower Target, then it transforms syntax that isn't native to that format, rewriting it into another syntactic form that is – Aluan Haddad Jul 24 '20 at 04:51
  • So then the question is, how do you use Angular with ES2020 with optional chaining, particularly when you need other 2020 features? Is there any way to tell Typescript to rewrite optional chaining while retaining the other features you need? – Trevortni Jan 04 '22 at 21:45

1 Answers1

3

Using Optional-Chaining in Angular 10 while targeting es2020 will result in the error 'Module parse failed: Unexpected token'

Current Workaround is to target es2019

JimbobTheSailor
  • 1,441
  • 1
  • 12
  • 21