Click to see the query in the CodeQL repository
In TypeScript, certain keywords have special meanings for member declarations, and misusing them can create confusion:
In classes, use constructor rather than new to declare constructors. Using new within a class creates a method named “new” and not a constructor signature.
In interfaces, use new rather than constructor to declare constructor signatures. Using constructor within an interface creates a method named “constructor” and not a constructor signature.
Similarly, the keyword function is used to declare functions in some contexts. However, using the name function for a class or interface member declaration declares a method named “function”. When these keywords are misused, TypeScript will interpret them as regular method names rather than their intended special syntax, leading to code that may not work as expected.
Consider following these guidelines for clearer code:
For classes, use constructor to declare constructors.
For interfaces, use new to declare constructor signatures (call signatures that create new instances).
Avoid accidentally creating methods named function by misusing the function keyword within class or interface declarations.
The following examples show common mistakes when using these keywords:
This interface mistakenly uses constructor, which creates a method named “constructor” instead of a constructor signature:
Use new for constructor signatures in interfaces:
This class mistakenly uses new, which creates a method named “new” instead of a constructor:
Use constructor for constructors in classes:
This interface uses function as a method name, which declares a method named “function” rather than declaring a function:
Use a descriptive method name instead:
TypeScript Handbook: Classes - Constructors.
TypeScript specification: Constructor Type Literals.
TypeScript specification: Constructor Parameters.