noMisleadingInstantiator
¥Summary
-
规则生效日期:
v1.3.0¥Rule available since:
v1.3.0 -
诊断类别:
lint/suspicious/noMisleadingInstantiator¥Diagnostic Category:
lint/suspicious/noMisleadingInstantiator -
此规则为推荐规则,默认启用。
¥This rule is recommended, which means is enabled by default.
-
此规则没有修复方案。
¥This rule doesn’t have a fix.
-
此规则的默认严重级别为 error。
¥The default severity of this rule is error.
-
来源:
¥Sources:
¥How to configure
{ "linter": { "rules": { "suspicious": { "noMisleadingInstantiator": "error" } } }}¥Description
强制在创建内置错误时传递消息值。
¥Enforce proper usage of new and constructor.
在 JavaScript 中,类利用 constructor 方法来初始化新实例。另一方面,TypeScript 接口可以描述具有 new() 方法签名的类类型,尽管这种模式在实际代码中并不常见。开发者,尤其是 JavaScript 或 TypeScript 新手,可能偶尔会混淆 constructor 和 new 的使用。此规则在以下情况下触发警告:
¥In JavaScript, classes utilize the constructor method to initialize a new instance. On the other hand, TypeScript interfaces can describe a class type with a new() method signature, though this pattern is not commonly seen in real-world code. Developers, especially those new to JavaScript or TypeScript, might occasionally confuse the use of constructor with new.
This rule triggers warnings in the following scenarios:
-
当类具有名为
new的方法时。¥When a class has a method named
new. -
当接口定义返回接口类型的名为
constructor或new的方法时。¥When an interface defines a method named
constructorornewthat returns the interface type. -
当类型别名具有
constructor方法时。¥When a type alias has a
constructormethod.
如果你有意想要一个带有 new 方法的类,并且你确信没有人会在你的代码中将其误认为是 constructor,则不应使用此规则。
¥You should not use this rule if you intentionally want a class with a new method, and you’re confident nobody working in your code will mistake it with an constructor.
¥Examples
¥Invalid
interface I { new (): I; constructor(): void;}code-block.ts:2:3 lint/suspicious/noMisleadingInstantiator ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Don’t use the new method in interfaces.
1 │ interface I {
> 2 │ new (): I;
│ ^^^^^^^^^^
3 │ constructor(): void;
4 │ }
ℹ new in an interface suggests it’s instantiable, which is incorrect. The returned type should different from the constructor’s type.
class C { new(): C;}code-block.ts:2:3 lint/suspicious/noMisleadingInstantiator ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Don’t use the new method in classes.
1 │ class C {
> 2 │ new(): C;
│ ^^^^^^^^^
3 │ }
4 │
ℹ new is typically used to instantiate objects. In classes, its usage can be misleading.
¥Valid
declare class C { constructor();}
interface I { new (): C;}¥Related links
Biome v2.1 中文网 - 粤ICP备13048890号