noMisleadingInstantiator
诊断类别:lint/suspicious/noMisleadingInstantiator
¥Diagnostic Category: lint/suspicious/noMisleadingInstantiator
自从:v1.3.0
¥Since: v1.3.0
来源:
¥Sources:
-
与以下相同:
@typescript-eslint/no-misused-new
¥Same as:
@typescript-eslint/no-misused-new
强制在创建内置错误时传递消息值。
¥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
constructor
ornew
that returns the interface type. -
当类型别名具有
constructor
方法时。¥When a type alias has a
constructor
method.
如果你有意想要一个带有 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
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.
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
¥Related links