Skip to main content

no-misused-new

Enforce valid definition of new and constructor.

ESLint 配置 中扩展"plugin:@typescript-eslint/recommended" 可启用此规则。

JavaScript 类可以定义在新建类实例时运行的 constructor 方法。TypeScript 允许描述静态类对象的接口定义 new() 方法(尽管这在现实世界的代码中很少使用)。不熟悉 JavaScript 类和/或 TypeScript 接口的开发者有时可能会混淆何时使用 constructornew

¥JavaScript classes may define a constructor method that runs when a class instance is newly created. TypeScript allows interfaces that describe a static class object to define a new() method (though this is rarely used in real world code). Developers new to JavaScript classes and/or TypeScript interfaces may sometimes confuse when to use constructor or new.

此规则报告类方法何时声明该类名的返回类型而不是 new

¥This rule reports when a class defines a method named new or an interface defines a method named constructor.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-misused-new": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

declare class C {
new(): C;
}

interface I {
new (): I;
constructor(): void;
}
Open in Playground

选项

该规则不可配置。

何时不使用它

¥When Not To Use It

如果你有意想要一个具有 new 方法的类,并且你确信没有人会在你的代码中将其误认为构造函数,那么你可能不需要此规则。你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

¥If you intentionally want a class with a new method, and you're confident nobody working in your code will mistake it with a constructor, you might not want this rule. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

'## 资源'