Angular 4中如何修复"Cannot use 'new' with an expression whose type lacks a call or construct signature"错误?
Hey there! I totally get how frustrating it is when a tutorial's code doesn't compile—especially when you're just starting out with Angular. Let's break down this error and fix it together.
What's causing this error?
This TypeScript error pops up because you're trying to use new to instantiate something that isn't a proper class with a valid constructor signature. Angular (and modern TypeScript) enforces stricter type checks by default, so older tutorial code that used loose constructor patterns (like plain functions acting as constructors) won't fly anymore.
Step-by-step fixes
Here are the most common scenarios and how to fix them:
Replace old-style constructor functions with standard classes
A lot of older tutorials might have used function-based constructors, which TypeScript now flags in strict mode. For example:// ❌ Old tutorial code that fails now export function Product(name: string, price: number) { this.name = name; this.price = price; }Convert this to a proper class with an explicit constructor:
// ✅ Correct class syntax that passes compilation export class Product { constructor(public name: string, public price: number) {} }Now you can safely instantiate it:
const myProduct = new Product('Laptop', 999);Check if you're importing the right thing
Sometimes the error happens because you accidentally imported an object or function instead of a class. For example:// ❌ Exporting an object instead of a class export const Product = { defaultName: 'Unknown', defaultPrice: 0 };If you try
new Product()here, you'll get the error. Fix this by changing the export to a class, or just use the object directly withoutnew.Verify your TypeScript strict mode settings
Angular projects default tostrict: trueintsconfig.json, which enforces these stricter rules. While you could disable strict mode temporarily, I don't recommend it—learning with strict mode enabled will help you write cleaner, more maintainable Angular code long-term.
Example in an Angular component
Here's how this looks in a real Angular component to make it concrete:
import { Component } from '@angular/core'; // Define your class properly class TodoItem { constructor(public task: string, public isDone: boolean) {} } @Component({ selector: 'app-todo-list', template: ` <ul> <li *ngFor="let item of todoItems"> {{ item.task }} - {{ item.isDone ? 'Completed' : 'Pending' }} </li> </ul> ` }) export class TodoListComponent { todoItems = [ new TodoItem('Set up Angular project', true), new TodoItem('Fix compilation errors', false) ]; }
This code will compile without any issues, and you'll be back on track with your tutorial!
内容的提问来源于stack exchange,提问作者pitchblack408

