升级至Angular 10后出现Class constructor需用new调用的报错求助
Hey there! Let’s work through this frustrating error you’re seeing post-upgrade. This issue almost always boils down to mismatched tooling versions, outdated dependencies, or misconfigured TypeScript settings—here’s how to fix it step by step:
1. Verify Your TypeScript Version
Angular 10 requires TypeScript 3.9.x (specifically ~3.9.7 is the recommended version for Angular 10.2.x). If your TypeScript version is too old or too new, it can cause class constructor transpilation issues.
- Open your
package.jsonand check thetypescriptentry. - Update it if needed:
"typescript": "~3.9.7" - Run
npm installoryarn installto sync the version.
2. Fix Your tsconfig.json Settings
Incorrect TypeScript compiler options can break class instantiation. Double-check these settings in your root tsconfig.json:
- Ensure
targetis set to at least"es2015"(ES5 doesn’t support some modern class syntax that Angular 10 relies on):"compilerOptions": { "target": "es2015", "experimentalDecorators": true, "emitDecoratorMetadata": true, "downlevelIteration": true } - Save the file, then restart your dev server with
ng serve --delete-output-pathto apply changes.
3. Upgrade Third-Party Dependencies
Outdated libraries (especially those that interact with Angular’s forms module) are a common culprit. Any package that extends or uses FormControl, FormGroup, etc., needs to be compatible with Angular 10.
- Use
npm outdatedoryarn outdatedto spot dependencies that need updating. - Pay extra attention to form-related libraries (e.g., form validation libraries, UI component kits with form inputs) and upgrade them to versions explicitly marked as compatible with Angular 10.
4. Clear Build & Package Caches
Stale cache can hold onto old transpiled code that conflicts with the new Angular version. Try these steps:
- Delete your
node_modulesfolder and lock file (package-lock.jsonoryarn.lock). - Run
npm clean-install(oryarn installfor Yarn users) to do a fresh install. - Clear Angular’s build cache with
ng build --cleanor add the--delete-output-pathflag to yourng servecommand.
5. Check Custom Form Code
If you’ve built custom form controls or extended Angular’s form classes, make sure you’re always using the new keyword when instantiating FormControl, FormGroup, etc. Accidentally writing FormControl(...) instead of new FormControl(...) will throw this error, especially with stricter transpilation in Angular 10.
内容的提问来源于stack exchange,提问作者Francesco Borzi

