Upgrading Typescript on Angular 8
If we try using the latest version of Typescript with Angular 8, during compilation we will see the following error
Angular Compiler requires TypeScript >= 3.4.0 and <3.6.0
This stop us from using new Typescript features like
- Stricter generators from TS 3.6 - https://www.typescriptlang.org/docs/handbook/release-notes/overview.html#typescript-36
- Null coalescing from TS 3.7 - https://www.typescriptlang.org/docs/handbook/release-notes/overview.html#typescript-37
- ECMAscript 2020 features from TS 3.8 - https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html
If you have been using Typescript from pre 1.x days, you know that the frequency of TS upgrades matters, if you want to avoid the dreaded breaking changes. I've worked on projects which were stuck using specific version of Typescript cause the effort/cost of code refactoring was too high.
I recently upgraded Typescript from 3.5.3
to 3.8.3
(latest TS version while publishing this post) on a fairly large Angular 8 project. These are the steps I followed -
npm install typescript@3.8.3
- Update
tsconfig.json
to force Angular compiler to skip Typescript version check
{
"compileOnSave": false,
"angularCompilerOptions": {
"disableTypeScriptVersionCheck": true
},
"compilerOptions": {
"baseUrl": "./"
....
....
}
}
- Build and run your tests to verify if everything is working as expected.
This is where I ran into following error -
Uncaught ReferenceError: __importDefault is not defined
To workaround this issue, I add following to src/polyfills.ts
file
(window as any).__importDefault = mod => {
return mod && mod.__esModule ? mod : { default: mod };
};
We use an custom build script which will run linting, followed by unit tests before generating production ready bundle. Things were failing at multiple steps for various reasons (did a complete upgrade of all dependencies along with TS upgrade) but in the end, the experience was worth it. Angular has reasons for enforcing such strict checks (I do disagree with some of Angular CLI's philosophy but that's for another post). The latest version of Typescript works seamlessly with Angular 9. Just that older versions of Angular need to jump through few hoops to get it working.