noMisleadingInstantiator
此内容尚不支持你的语言。
Summary
Section titled “Summary”- Rule available since: v1.3.0
- Diagnostic Category: lint/suspicious/noMisleadingInstantiator
- This rule is recommended, which means is enabled by default.
- This rule doesn’t have a fix.
- The default severity of this rule is error.
- Sources:
How to configure
Section titled “How to configure”{  "linter": {    "rules": {      "suspicious": {        "noMisleadingInstantiator": "error"      }    }  }}Description
Section titled “Description”Enforce proper usage of new and constructor.
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:
- When a class has a method named new.
- When an interface defines a method named constructorornewthat returns the interface type.
- When a type alias has a constructormethod.
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
Section titled “Examples”Invalid
Section titled “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.
  
declare class C {  constructor();}
interface I {  new (): C;}Related links
Section titled “Related links”Copyright (c) 2023-present Biome Developers and Contributors.