TypeScript Coding Violations
Require that member overloads be consecutive
Description: Grouping overloaded members together can improve readability of the code.
Requires using either T[]
or Array<T>
for arrays
Description: Using the same style for array definitions across your codebase makes it easier for your developers to read and understand the types.
Disallows awaiting a value that is not a Thenable
Description: This rule disallows awaiting a value that is not a "Thenable" (an object which has then
method, such as a Promise).
Bans @ts-<directive>
comments from being used or requires descriptions after directive
Description: TypeScript provides several directive comments that can be used to alter how it processes files.
Bans // tslint:<rule-flag>
comments from being used
Description: Useful when migrating from TSLint to ESLint. Once TSLint has been removed, this rule helps locate TSLint annotations (e.g. // tslint:disable
).
Bans specific types from being used
Description: Some builtin types have aliases, some types are considered dangerous or harmful.
Enforce consistent brace style for blocks
Description: Brace style is closely related to indent style in programming and describes the placement of braces relative to their control statement and body. While no style is considered better than the other, most developers agree that having a consistent style throughout a project is important for its long-term maintainability. This rule enforces consistent brace style for blocks.
Ensures that literals on classes are exposed in a consistent style
Description: When writing TypeScript applications, it's typically safe to store literal values on classes using fields with the readonly
modifier to prevent them from being reassigned.
Require or disallow trailing comma
Description: Enforces consistent use of trailing commas in object and array literals.
Enforces consistent spacing before and after commas
Description: Εnforces consistent spacing before and after commas in variable declarations, array literals, object literals, function parameters, and sequences.
Enforce or disallow the use of the record type
Description: TypeScript supports defining object show keys can be flexible using an index signature. TypeScript also has a builtin type named Record
to create an empty object defining only an index signature. For example, the following types are equal:
Specify generic type arguments
Description: Enforces specifying generic type arguments on type annotation or constructor name of a constructor call.
Enforces consistent usage of type assertions
Description: Αims to standardize the use of type assertion style across the codebase. Type assertions are also commonly referred as 'type casting' in TypeScript. In addition to ensuring that type assertions are written in a consistent way, this rule also makes the codebase more type-safe.
Consistent with type definition either interface
or type
Description: There are two ways to define a type.
Proper use of type export
Description: Enforces consistent usage of type exports.
Enforces consistent usage of type imports
Description: TypeScript 3.8 added support for type-only imports.
Enforce default parameters to be last
Description: Enforces default parameters to be the last of parameters.
enforce dot notation whenever possible
Description: Aims at maintaining code consistency and improving code readability by encouraging use of the dot notation style whenever possible. As such, it warns when it encounters an unnecessary use of square-bracket notation.
Require explicit return types on functions and class methods
Description: Explicit types for function return values makes it clear to any calling code what type is returned.
Require explicit accessibility modifiers on class properties and methods
Description: Leaving off accessibility modifier and making everything public can make
Require explicit return and argument types on exported functions' and classes' public class methods
Description: Explicit types for function return values and arguments makes it clear to any calling code what is the module boundary's input and output.
Require or disallow spacing between function identifiers and their invocations
Description: Requires or disallows spaces between the function name and the opening parenthesis that calls it.
Enforce consistent indentation
Description: Enforces a consistent indentation style. The default style is 4 spaces.
require or disallow initialization in variable declarations
Description: Aims at enforcing or eliminating variable initializations during declaration.
Enforce consistent spacing before and after keywords
Description: Enforces consistent spacing around keywords and keyword-like tokens: as (in module declarations), async (of async functions), await (of await expressions), break, case, catch, class, const, continue, debugger, default, delete, do, else, export, extends, finally, for, from (in module declarations), function, get (of getters), if, import, in, instanceof, let, new, of (in for-of statements), return, set (of setters), static, super, switch, this, throw, try, typeof, var, void, while, with, and yield.
Require or disallow an empty line between class members
Description: This rule improves readability by enforcing lines between class members. It will not check empty lines before the first member and after the last member. This rule require or disallow an empty line between class members.
Require a specific member delimiter style for interfaces and type literals
Description: Enforces a consistent member delimiter style in interfaces and type literals. There are three member delimiter styles primarily used in TypeScript:
Require a consistent member declaration order
Description: A consistent ordering of fields, methods and constructors can make interfaces, type literals, classes and class expressions easier to read, navigate and edit.
Enforces using a particular method signature syntax.
Description: There are two ways to define an object/interface function property.
Enforces naming conventions for everything across a codebase
Description: Enforcing naming conventions helps keep the codebase consistent, and reduces overhead when thinking about how to name a variable.
Disallow generic Array
constructors
Description: Use of the Array constructor to construct a new array is generally discouraged in favor of array literal notation because of the single-argument pitfall and because the Array global may be redefined. This rule disallows Array constructors.
Requires that .toString
Description: JavaScript will call toString()
on an object when it is converted to a string, such as when +
adding to a string or in ${}
template literals.
Disallow non-null assertion in locations that may be confusing
Description: Using a non-null assertion (!) next to an assign or equals check (= or == or ===) creates code that is confusing as it looks similar to a not equals check (!= !==). This rule disallows non-null assertion in locations that may be confusing.
Requires expressions of type void to appear in statement position
Description: Returning the results of an expression whose type is void can be misleading.
Disallow duplicate class members
Description: If there are declarations of the same name in class members, the last declaration overwrites other declarations silently. It can cause unexpected behaviors. This rule is aimed to flag the use of duplicate names in class members.
Disallow duplicate imports
Description: Using a single import statement per module will make the code clearer because you can see everything being imported from that module on one line. This rule requires that all imports from a single module that can be merged exist in a single import statement.
Disallow the delete operator with computed key expressions
Description: Deleting dynamically computed keys can be dangerous and in some cases not well optimized.
Disallow empty functions
Description: Empty functions can reduce readability because readers need to guess whether it's intentional or not. So writing a clear comment for empty functions is a good practice. This rule is aimed at eliminating empty functions.
Disallow the declaration of empty interfaces
Description: An empty interface is equivalent to its supertype. If the interface does not implement a supertype, then the interface is equivalent to an empty object ({}). In both cases it can be omitted.
Disallow usage of the any
type
Description: Using the any
type defeats the purpose of using TypeScript.
Disallow extra non-null assertion
Description: Using non-null assertions cancels the benefits of the strict null-checking mode.
Disallow unnecessary parentheses
Description: This rule restricts the use of parentheses to only where they are necessary.
Disallow unnecessary semicolons
Description: Typing mistakes and misunderstandings about where semicolons are required can lead to semicolons that are unnecessary. While not technically an error, extra semicolons can cause confusion when reading code. This rule disallows unnecessary semicolons.
Forbids the use of classes as namespaces
Description: This rule warns when a class is accidentally used as a namespace.
Requires Promise-like values to be handled appropriately
Description: This rule forbids usage of Promise-like values in statements without handling
Disallow iterating over an array with a for-in loop
Description: This rule prohibits iterating over an array with a for-in loop.
Disallow usage of the implicit any
type in catch clauses
Description: TypeScript 4.0 added support for adding an explicit any
or unknown
type annotation on a catch clause variable.
Disallow the use of eval
Description: It's considered a good practice to avoid using eval()
. There are security and performance implications involved with doing so, which is why many linters recommend disallowing eval()
. However, there are some other ways to pass a string and have it interpreted as JavaScript code that have similar concerns.
Disallows explicit type declarations for variables or parameters initialized to a number, string, or boolean
Description: Explicit types where they can be easily inferred may add unnecessary verbosity.
Disallow this
keywords outside of classes or class-like objects
Description: Under the strict mode, this keywords outside of classes or class-like objects might be undefined and raise a TypeError. This rule aims to flag usage of this keywords outside of classes or class-like objects.
Disallows usage of void
type outside of generic or return types
Description: Disallows usage of void
type outside of return types or generic type arguments.
Disallow function declarations that contain unsafe references inside loop statements
Description: Writing functions within loops tends to result in errors due to the way the function creates a closure around the loop. This error is raised to highlight a piece of code that may not work as expected to and could also indicate a misunderstanding of how the language works. The code may run without any problems, but in some situations it could behave unexpectedly. This rule disallows any function within a loop that contains unsafe references (e.g. to modified variables from the outer scope).
Disallow literal numbers that lose precision
Description: Numbers are stored as double-precision floating-point numbers according to the IEEE 754 standard. Because of this, numbers can only retain accuracy up to a certain amount of digits. If the programmer enters additional digits, those digits will be lost in the conversion to the Number type and will result in unexpected behavior. This rule disallows the use of number literals that immediately lose precision at runtime.
Disallow magic numbers
Description: 'Magic numbers' are numbers that occur multiple times in code without an explicit meaning. They should preferably be replaced by named constants. The no-magic-numbers rule aims to make code more readable and refactoring easier by ensuring that special numbers are declared as constants to make their meaning explicit.
Disallow the void
operator except when used to discard a value
Description: This rule catches API changes where previously a value was being discarded.
Enforce valid definition of new
and constructor
Description: Warns on apparent attempts to define constructors for interfaces or new
for classes.
Avoid using promises in places not designed to handle them
Description: This rule forbids using promises in places where the TypeScript compiler
Disallow the use of custom TypeScript modules and namespaces
Description: Custom TypeScript modules (module foo {}
) and namespaces (namespace foo {}
) are considered outdated
Disallows using a non-null assertion after an optional chain expression
Description: Optional chain expressions are designed to return undefined if the optional property is nullish. Using non-null assertions after an optional chain expression is wrong, and introduces a serious type safety hole into the code.
Disallows non-null assertions using the !
postfix operator
Description: Using non-null assertions cancels the benefits of the strict null-checking mode. This rule disallows non-null assertions using the !
postfix operator
Disallow the use of parameter properties in class constructors
Description: Parameter properties can be confusing to those new to TypeScript as they are less explicit than other ways
Disallow variable redeclaration
Description: It's possible to redeclare the same variable name using var. This can lead to confusion as to where the variable is actually declared and initialized. This rule is aimed at eliminating variables that have multiple declarations in the same scope.
Disallows invocation of `require
Description: Prefer the newer ES6-style imports over require()
.
Disallow variable declarations from shadowing variables declared in the outer scope
Description: Shadowing is the process by which a local variable shares the same name as a variable in its containing scope. This rule aims to eliminate shadowed variable declarations.
Disallow aliasing this
Description: This rule prohibits assigning variables to this
.
Disallow throwing literals as exceptions
Description: It is considered good practice to only throw
the Error
object itself or an object using the Error
object as base objects for user-defined exceptions.
Disallow the use of type aliases
Description: In TypeScript, type aliases serve three purposes:
Flags unnecessary equality comparisons against boolean literals
Description: Comparing boolean values to boolean literals is unnecessary, those comparisons result in the same booleans. Using the boolean values directly, or via a unary negation (!value
), is more concise and clearer.
Prevents conditionals where the type is always truthy or always falsy
Description: Any expression being used as a condition must be able to evaluate as truthy or falsy in order to be considered "necessary". Conversely, any expression that always evaluates to truthy or always evaluates to falsy, as determined by the type of the expression, is considered unnecessary and will be flagged by this rule.
Warns when a namespace qualifier is unnecessary
Description: This rule aims to let users know when a namespace or enum qualifier is unnecessary, whether used for a type or for a value.
Enforces that type arguments will not be used if not required
Description: Warns if an explicitly specified type argument is the default for that type parameter.
Warns if a type assertion does not change the type of an expression
Description: This rule prohibits using a type assertion that does not change the type of an expression.
Disallows unnecessary constraints on generic types
Description: Type parameters (<T>
) may be 'constrained' with an extends keyword. When not provided, type parameters happen to default to: unknown or any. It is therefore redundant to extend from these types in later versions of TypeScript.
Disallow calling a function with a value with type any
Description: This rule disallows calling a function with any in its arguments. That includes spreading arrays or tuples with any typed elements as function arguments.
Disallows assigning any to variables and properties
Description: Despite your best intentions, the any
type can sometimes leak into your codebase.
Disallows calling an any type value
Description: Despite your best intentions, the any
type can sometimes leak into your codebase.
Disallows member access on any typed variables
Description: Despite your best intentions, the any
type can sometimes leak into your codebase.
Disallow empty exports that don't change anything in a module file
Description: This rule reports an 'export {}' that doesn't do anything in a file already using ES modules.
Disallows returning any from a function
Description: Despite your best intentions, the any
type can sometimes leak into your codebase.
Disallow unused expressions
Description: An unused expression which has no effect on the state of the program indicates a logic error. This rule aims to eliminate unused expressions which have no effect on the state of the program.
Disallow unused variables and arguments
Description: Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.
Disallow unused variables
Description: Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers. This rule is aimed at eliminating unused variables, functions, and function parameters.
Disallow the use of variables before they are defined
Description: This rule will warn when it encounters a reference to an identifier that has not yet been declared.
Disallow unnecessary constructors
Description: This rule flags class constructors that can be safely removed without changing how the class works.
Disallows the use of require statements except in import statements
Description: In other words, the use of forms such as let foo = require("foo")
are banned. Instead use ES6 style imports or import foo = require("foo")
imports.
Prefers a non-null assertion over explicit type cast when possible
Description: This rule detects when an as
cast is doing the same job as a !
would, and suggests fixing the code to be an !
.
Enforce consistent spacing inside braces
Description: While formatting preferences are very personal, a number of style guides require or disallow spaces between curly braces. This rule enforces consistent spacing inside braces of object literals, destructuring assignments, and import/export specifiers.
Padding line between statements
Description: Require or disallow padding lines between statements.
Require parameter properties
Description: Require or disallow parameter properties in class constructors.
Prefer usage of as const
over literal type
Description: This rule recommends usage of const
assertion when type primitive value is equal to type.
Prefer initializing each enums member value
Description: This rule recommends having each enum
s member value explicitly initialized.
Prefer a ‘for-of’ loop over a standard ‘for’ loop if the index is only used to access the array being iterated
Description: This rule recommends a for-of loop when the loop index is only used to read from an array that is being iterated.
for (let j = 0; j < arr.length; i++) {
console.log(array[ij]);
}
for (const y of array) {
console.log(y);
}
Use function types instead of interfaces with call signatures
Description: This rule suggests using a function type instead of an interface or object type literal with a single call signature.
Enforce includes
method over indexOf
method
Description: Until ES5, we were using String#indexOf
method to check whether a string contains an arbitrary substring or not.
Require that all enum members be literal values to prevent unintended enum member name shadow issues
Description: TypeScript allows the value of an enum member to be many different kinds of valid JavaScript expressions. However, because enums create their own scope whereby each enum member becomes a variable in that scope, unexpected values could be used at runtime. Example:
Require the use of the namespace
keyword instead of the module
keyword to declare custom TypeScript modules
Description: In an effort to prevent further confusion between custom TypeScript modules and the new ES2015 modules, starting
Enforce the usage of the nullish coalescing operator instead of logical chaining
Description: TypeScript 3.7 added support for the nullish coalescing operator.
Prefer using concise optional chain expressions instead of chained logical ands
Description: TypeScript 3.7 added support for the optional chain operator.
Requires that function parameters are typed as readonly to prevent accidental mutation of inputs
Description: Mutating function arguments can lead to confusing, hard to debug behavior.
Requires that private members are marked as readonly
if they're never modified outside of the constructor
Description: This rule enforces that private members are marked as readonly
if they're never modified outside of the constructor.
Prefer using type parameter when calling Array#reduce
instead of casting
Description: It's common to call Array#reduce
with a generic type, such as an array or object, as the initial value.
Enforce that RegExp#exec
is used instead of String#match
if no global flag is provided
Description: RegExp#exec
is faster than String#match
and both work the same when not using the /g
flag.
Proper use of this
Description: Enforce that this
is used when only this
type is returned.
Enforce the use of String#startsWith
and String#endsWith
instead of other equivalent methods of checking substrings
Description: There are multiple ways to verify if a string starts or ends with a specific string, such as foo.indexOf('bar') === 0
.
let boo: string;
// starts with
boo[0] === 'a';
boo.substring(0, 10) === 'tab';
// ends with
boo.slice(-3) === 'tab';
boo.startsWith('tab');
boo.endsWith('tab');
Recommends using @ts-expect-error
over @ts-ignore
Description: TypeScript allows you to suppress all errors on a line by placing a single-line comment or a comment block line starting with @ts-ignore
immediately before the erroring line.
Requires any function or method that returns a Promise to be marked async
Description: Requires any function or method that returns a Promise to be marked async.
Enforce the consistent use of either backticks, double, or single quotes
Description: This rule enforces the consistent use of either backticks, double, or single quotes.
Requires Array#sort
calls to always provide a compareFunction
Description: This rule prevents invoking the Array#sort()
method without providing a compare
argument.
Disallow async functions which have no await
expression
Description: Asynchronous functions that don't use await might not need to be asynchronous functions and could be the unintentional result of refactoring. This rule warns async functions which have no await expression.
When adding two variables, operands must both be of type number or of type string
Description: Examples of correct code:
Enforce template literal expressions to be of string type
Description: Examples of correct code:
Enforces consistent returning of awaited values
Description: Returning an awaited promise can make sense for better stack trace information as well as for consistent error handling (returned promises will not be caught in an async function try/catch).
Require or disallow semicolons instead of ASI
Description: This rule enforces consistent use of semicolons after statements.
Enforces that members of a type union/intersection are sorted alphabetically
Description: Sorting union (|
) and intersection (&
) types can help:
Enforce constituents of a type union/intersection to be sorted alphabetically
Description: This rule reports on any types that aren't sorted alphabetically.
Enforces consistent spacing before function parenthesis
Description: When formatting a function, whitespace is allowed between the function name or function keyword and the opening paren. Named functions also require a space between the function keyword and the function name, but anonymous functions require no whitespace. This rule aims to enforce consistent spacing before function parentheses and as such, will warn whenever whitespace doesn't match the preferences specified.
This rule is aimed at ensuring there are spaces around infix operators.
Description: This rule extends the base eslint/space-infix-ops
rule.
Restricts the types allowed in boolean expressions
Description: Forbids usage of non-boolean types in expressions where a boolean is expected.
Exhaustiveness checking in switch with union type
Description: Union type may have a lot of parts. It's easy to forget to consider all cases in switch. This rule reminds which parts are missing. If domain of the problem requires to have only a partial switch, developer may explicitly add a default clause.
Sets preference level for triple slash directives versus ES6-style import declarations
Description: Use of triple-slash reference type directives is discouraged in favor of the newer import
style. This rule allows you to ban use of /// <reference path="" />
, /// <reference types="" />
, or /// <reference lib="" />
directives.
Require consistent spacing around type annotations
Description: Spacing around type annotations improves readability of the code. Although the most commonly used style guideline for type annotations in TypeScript prescribes adding a space after the colon, but not before it, it is subjective to the preferences of a project. For example:
Requires type annotations to exist
Description: TypeScript cannot always infer types for all places in code.
Enforces unbound methods are called with their expected scope
Description: Warns when a method is used outside of a method call.
Warns for any two overloads that could be unified into one by using a union or an optional/rest parameter
Description: Warns for any two overloads that could be unified into one by using a union or an optional/rest parameter.