Skip to main content

TypeScript Coding Violations

Cyclopt analyzes your TypeScript code to identify coding and security violations. Each check below lists its Rule ID, a description, and its source.

tip

Use a check's Rule ID to silence a finding in code with a cyclopt-ignore comment, or to exclude it project-wide in the configuration file.


Disallows invocation of 'require

Rule ID: @typescript-eslint/

Description: Prefer the newer ES6-style imports over require().

Bad Example
const foo = require("foo");
Good Example
import foo from "foo";

Require that member overloads be consecutive

Rule ID: @typescript-eslint/adjacent-overload-signatures

Description: Grouping overloaded members together can improve readability of the code.

Bad Example
interface Foo {
foo(s: string): void;
bar(): void;
foo(n: number): void;
}
Good Example
interface Foo {
foo(s: string): void;
foo(n: number): void;
bar(): void;
}

Requires using either T[] or Array<T> for arrays

Rule ID: @typescript-eslint/array-type

Description: Using the same style for array definitions across your codebase makes it easier for your developers to read and understand the types.

Bad Example
const x: Array<number> = [1, 2, 3];
Good Example
const x: number[] = [1, 2, 3];

Disallows awaiting a value that is not a Thenable

Rule ID: @typescript-eslint/await-thenable

Description: This rule disallows awaiting a value that is not a "Thenable" (an object which has then method, such as a Promise).

Bad Example
async function f() {
await 42;
}
Good Example
async function f() {
await Promise.resolve(42);
}

Bans @ts-<directive> comments from being used or requires descriptions after directive

Rule ID: @typescript-eslint/ban-ts-comment

Description: TypeScript provides several directive comments that can be used to alter how it processes files.

Bad Example
// @ts-ignore
const x: number = 'oops';
Good Example
// @ts-expect-error: value is intentionally mistyped for the demo
const x: number = 'oops';

Bans // tslint:<rule-flag> comments from being used

Rule ID: @typescript-eslint/ban-tslint-comment

Description: Useful when migrating from TSLint to ESLint. Once TSLint has been removed, this rule helps locate TSLint annotations (e.g. // tslint:disable).

Bad Example
// tslint:disable-next-line
const x = 1;
Good Example
const x = 1;

Bans specific types from being used

Rule ID: @typescript-eslint/ban-types

Description: Some builtin types have aliases, some types are considered dangerous or harmful.

Bad Example
let value: String = 'hello';
Good Example
let value: string = 'hello';

Enforce consistent brace style for blocks

Rule ID: @typescript-eslint/brace-style

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

Rule ID: @typescript-eslint/class-literal-property-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.

Bad Example
class Foo {
get bar() {
return 'baz';
}
}
Good Example
class Foo {
readonly bar = 'baz';
}

Require or disallow trailing comma

Rule ID: @typescript-eslint/comma-dangle

Description: Enforces consistent use of trailing commas in object and array literals.

Enforces consistent spacing before and after commas

Rule ID: @typescript-eslint/comma-spacing

Description: Εnforces consistent spacing before and after commas in variable declarations, array literals, object literals, function parameters, and sequences.

Specify generic type arguments

Rule ID: @typescript-eslint/consistent-generic-constructors

Description: Enforces specifying generic type arguments on type annotation or constructor name of a constructor call.

Bad Example
const map: Map<string, number> = new Map();
Good Example
const map = new Map<string, number>();

Enforce or disallow the use of the record type

Rule ID: @typescript-eslint/consistent-indexed-object-style

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:

Bad Example
interface Foo {
[key: string]: number;
}
Good Example
type Foo = Record<string, number>;

Enforces consistent usage of type assertions

Rule ID: @typescript-eslint/consistent-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.

Bad Example
const x = <string>value;
Good Example
const x = value as string;

Consistent with type definition either interface or type

Rule ID: @typescript-eslint/consistent-type-definitions

Description: There are two ways to define a type.

Bad Example
type Foo = {
x: number;
};
Good Example
interface Foo {
x: number;
}

Proper use of type exports

Rule ID: @typescript-eslint/consistent-type-exports

Description: Enforces consistent usage of type exports.

Enforces consistent usage of type imports

Rule ID: @typescript-eslint/consistent-type-imports

Description: TypeScript 3.8 added support for type-only imports.

Bad Example
import { Foo } from './foo';
let x: Foo;
Good Example
import type { Foo } from './foo';
let x: Foo;

Enforce default parameters to be last

Rule ID: @typescript-eslint/default-param-last

Description: Enforces default parameters to be the last of parameters.

Bad Example
function f(a = 1, b: number) {
return a + b;
}
Good Example
function f(b: number, a = 1) {
return a + b;
}

Enforce dot notation whenever possible

Rule ID: @typescript-eslint/dot-notation

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.

Bad Example
const value = obj['name'];
Good Example
const value = obj.name;

Require explicit return types on functions and class methods

Rule ID: @typescript-eslint/explicit-function-return-type

Description: Explicit types for function return values makes it clear to any calling code what type is returned.

Bad Example
function add(a: number, b: number) {
return a + b;
}
Good Example
function add(a: number, b: number): number {
return a + b;
}

Require explicit accessibility modifiers on class properties and methods

Rule ID: @typescript-eslint/explicit-member-accessibility

Description: Leaving off accessibility modifier and making everything public can make

Bad Example
class Foo {
name = 'x';
getName() {
return this.name;
}
}
Good Example
class Foo {
public name = 'x';
public getName(): string {
return this.name;
}
}

Require explicit return and argument types on exported functions' and classes' public class methods

Rule ID: @typescript-eslint/explicit-module-boundary-types

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.

Bad Example
export function f(a) {
return a;
}
Good Example
export function f(a: number): number {
return a;
}

Require or disallow spacing between function identifiers and their invocations

Rule ID: @typescript-eslint/func-call-spacing

Description: Requires or disallows spaces between the function name and the opening parenthesis that calls it.

Enforce consistent indentation

Rule ID: @typescript-eslint/indent

Description: Enforces a consistent indentation style. The default style is 4 spaces.

Require or disallow initialization in variable declarations

Rule ID: @typescript-eslint/init-declarations

Description: Aims at enforcing or eliminating variable initializations during declaration.

Bad Example
let x;
x = 5;
Good Example
let x = 5;

Enforce consistent spacing before and after keywords

Rule ID: @typescript-eslint/keyword-spacing

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

Rule ID: @typescript-eslint/lines-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

Rule ID: @typescript-eslint/member-delimiter-style

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

Rule ID: @typescript-eslint/member-ordering

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.

Rule ID: @typescript-eslint/method-signature-style

Description: There are two ways to define an object/interface function property.

Bad Example
interface Foo {
bar(x: number): void;
}
Good Example
interface Foo {
bar: (x: number) => void;
}

Enforces naming conventions for everything across a codebase

Rule ID: @typescript-eslint/naming-convention

Description: Enforcing naming conventions helps keep the codebase consistent, and reduces overhead when thinking about how to name a variable.

Disallow generic Array constructors

Rule ID: @typescript-eslint/no-array-constructor

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.

Bad Example
const arr = new Array(1, 2, 3);
Good Example
const arr = [1, 2, 3];

Disallow non-null assertion in locations that may be confusing

Rule ID: @typescript-eslint/no-confusing-non-null-assertion

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.

Bad Example
declare const a: string | null;
const b = a! == "x";
Good Example
declare const a: string | null;
const b = (a!) == "x";

Requires expressions of type void to appear in statement position

Rule ID: @typescript-eslint/no-confusing-void-expression

Description: Returning the results of an expression whose type is void can be misleading.

Bad Example
const log = () => console.log("bar");
Good Example
const log = () => {
console.log("bar");
};

Disallow duplicate class members

Rule ID: @typescript-eslint/no-dupe-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.

Bad Example
class A {
foo() {}
foo() {}
}
Good Example
class A {
foo() {}
bar() {}
}

Disallow duplicate imports

Rule ID: @typescript-eslint/no-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.

Bad Example
import { a } from "mod";
import { b } from "mod";
Good Example
import { a, b } from "mod";

Disallow the delete operator with computed key expressions

Rule ID: @typescript-eslint/no-dynamic-delete

Description: Deleting dynamically computed keys can be dangerous and in some cases not well optimized.

Bad Example
const obj: Record<string, number> = { a: 1 };
const key = "a";
delete obj[key];
Good Example
const obj = new Map<string, number>([["a", 1]]);
obj.delete("a");

Disallow empty functions

Rule ID: @typescript-eslint/no-empty-function

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.

Bad Example
function foo() {}
Good Example
function foo() {
// intentionally empty
}

Disallow the declaration of empty interfaces

Rule ID: @typescript-eslint/no-empty-interface

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.

Bad Example
interface Foo {}
Good Example
interface Foo {
value: string;
}

Disallow usage of the any type

Rule ID: @typescript-eslint/no-explicit-any

Description: Using the any type defeats the purpose of using TypeScript.

Bad Example
function foo(x: any): void {}
Good Example
function foo(x: unknown): void {}

Disallow extra non-null assertion

Rule ID: @typescript-eslint/no-extra-non-null-assertion

Description: Using non-null assertions cancels the benefits of the strict null-checking mode.

Bad Example
declare const foo: { bar: number } | null;
const x = foo!!.bar;
Good Example
declare const foo: { bar: number } | null;
const x = foo!.bar;

Disallow unnecessary parentheses

Rule ID: @typescript-eslint/no-extra-parens

Description: This rule restricts the use of parentheses to only where they are necessary.

Disallow unnecessary semicolons

Rule ID: @typescript-eslint/no-extra-semi

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

Rule ID: @typescript-eslint/no-extraneous-class

Description: This rule warns when a class is accidentally used as a namespace.

Bad Example
class Utils {
static add(a: number, b: number) {
return a + b;
}
}
Good Example
function add(a: number, b: number) {
return a + b;
}

Requires Promise-like values to be handled appropriately

Rule ID: @typescript-eslint/no-floating-promises

Description: This rule forbids usage of Promise-like values in statements without handling

Bad Example
declare function doWork(): Promise<void>;
doWork();
Good Example
declare function doWork(): Promise<void>;
void doWork();

Disallow iterating over an array with a for-in loop

Rule ID: @typescript-eslint/no-for-in-array

Description: This rule prohibits iterating over an array with a for-in loop.

Bad Example
const arr = [1, 2, 3];
for (const i in arr) {
console.log(arr[i]);
}
Good Example
const arr = [1, 2, 3];
for (const x of arr) {
console.log(x);
}

Disallow usage of the implicit any type in catch clauses

Rule ID: @typescript-eslint/no-implicit-any-catch

Description: TypeScript 4.0 added support for adding an explicit any or unknown type annotation on a catch clause variable.

Bad Example
try {
} catch (e) {
console.log(e);
}
Good Example
try {
} catch (e: unknown) {
console.log(e);
}

Disallows explicit type declarations for variables or parameters initialized to a number, string, or boolean

Rule ID: @typescript-eslint/no-inferrable-types

Description: Explicit types where they can be easily inferred may add unnecessary verbosity.

Bad Example
const count: number = 5;
Good Example
const count = 5;

Disallow this keywords outside of classes or class-like objects

Rule ID: @typescript-eslint/no-invalid-this

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.

Bad Example
function foo() {
console.log(this.a);
}
Good Example
class Foo {
a = 1;
foo() {
console.log(this.a);
}
}

Disallows usage of void type outside of generic or return types

Rule ID: @typescript-eslint/no-invalid-void-type

Description: Disallows usage of void type outside of return types or generic type arguments.

Bad Example
let x: void;
Good Example
let x: undefined;

Disallow function declarations that contain unsafe references inside loop statements

Rule ID: @typescript-eslint/no-loop-func

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).

Bad Example
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
Good Example
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}

Disallow literal numbers that lose precision

Rule ID: @typescript-eslint/no-loss-of-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.

Bad Example
const x = 9007199254740993;
Good Example
const x = 9007199254740993n;

Disallow magic numbers

Rule ID: @typescript-eslint/no-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.

Bad Example
function toSeconds(minutes: number) {
return minutes * 60;
}
Good Example
const SECONDS_PER_MINUTE = 60;
function toSeconds(minutes: number) {
return minutes * SECONDS_PER_MINUTE;
}

Disallow the void operator except when used to discard a value

Rule ID: @typescript-eslint/no-meaningless-void-operator

Description: This rule catches API changes where previously a value was being discarded.

Bad Example
function foo(): void {}
void foo();
Good Example
function foo(): void {}
foo();

Enforce valid definition of new and constructor

Rule ID: @typescript-eslint/no-misused-new

Description: Warns on apparent attempts to define constructors for interfaces or new for classes.

Bad Example
interface I {
new (): I;
}
Good Example
class I {
constructor() {}
}

Avoid using promises in places not designed to handle them

Rule ID: @typescript-eslint/no-misused-promises

Description: This rule forbids using promises in places where the TypeScript compiler

Bad Example
declare const p: Promise<boolean>;
if (p) {
}
Good Example
declare const p: Promise<boolean>;
if (await p) {
}

Disallow the use of custom TypeScript modules and namespaces

Rule ID: @typescript-eslint/no-namespace

Description: Custom TypeScript modules (module foo {}) and namespaces (namespace foo {}) are considered outdated

Bad Example
namespace Foo {
export const x = 1;
}
Good Example
export const x = 1;

Disallows using a non-null assertion after an optional chain expression

Rule ID: @typescript-eslint/no-non-null-asserted-optional-chain

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.

Bad Example
declare const foo: { bar?: number } | undefined;
const x = foo?.bar!;
Good Example
declare const foo: { bar?: number } | undefined;
const x = foo?.bar;

Disallows non-null assertions using the ! postfix operator

Rule ID: @typescript-eslint/no-non-null-assertion

Description: Using non-null assertions cancels the benefits of the strict null-checking mode. This rule disallows non-null assertions using the ! postfix operator

Bad Example
declare const foo: string | null;
const x = foo!.length;
Good Example
declare const foo: string | null;
const x = foo?.length;

Disallow the use of parameter properties in class constructors

Rule ID: @typescript-eslint/no-parameter-properties

Description: Parameter properties can be confusing to those new to TypeScript as they are less explicit than other ways

Bad Example
class Foo {
constructor(private name: string) {}
}
Good Example
class Foo {
private name: string;
constructor(name: string) {
this.name = name;
}
}

Disallow variable redeclaration

Rule ID: @typescript-eslint/no-redeclare

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.

Bad Example
var a = 1;
var a = 2;
Good Example
var a = 1;
a = 2;

Disallow variable declarations from shadowing variables declared in the outer scope

Rule ID: @typescript-eslint/no-shadow

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.

Bad Example
const a = 1;
function f() {
const a = 2;
return a;
}
Good Example
const a = 1;
function f() {
const b = 2;
return b;
}

Disallow aliasing this

Rule ID: @typescript-eslint/no-this-alias

Description: This rule prohibits assigning variables to this.

Bad Example
class Foo {
method() {
const self = this;
setTimeout(function () {
self.doWork();
});
}
}
Good Example
class Foo {
method() {
setTimeout(() => {
this.doWork();
});
}
}

Disallow throwing literals as exceptions

Rule ID: @typescript-eslint/no-throw-literal

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.

Bad Example
throw "something went wrong";
Good Example
throw new Error("something went wrong");

Disallow the use of type aliases

Rule ID: @typescript-eslint/no-type-alias

Description: In TypeScript, type aliases serve three purposes:

Flags unnecessary equality comparisons against boolean literals

Rule ID: @typescript-eslint/no-unnecessary-boolean-literal-compare

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.

Bad Example
declare const isDone: boolean;
if (isDone === true) {
}
if (isDone === false) {
}
Good Example
declare const isDone: boolean;
if (isDone) {
}
if (!isDone) {
}

Prevents conditionals where the type is always truthy or always falsy

Rule ID: @typescript-eslint/no-unnecessary-condition

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.

Bad Example
function foo(arg: string) {
if (arg) {
}
}
Good Example
function foo(arg: string | null) {
if (arg) {
}
}

Warns when a namespace qualifier is unnecessary

Rule ID: @typescript-eslint/no-unnecessary-qualifier

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.

Bad Example
enum A {
B,
C = A.B,
}
Good Example
enum A {
B,
C = B,
}

Enforces that type arguments will not be used if not required

Rule ID: @typescript-eslint/no-unnecessary-type-arguments

Description: Warns if an explicitly specified type argument is the default for that type parameter.

Bad Example
function f<T = number>(): T {
return 0 as T;
}
f<number>();
Good Example
function f<T = number>(): T {
return 0 as T;
}
f();

Warns if a type assertion does not change the type of an expression

Rule ID: @typescript-eslint/no-unnecessary-type-assertion

Description: This rule prohibits using a type assertion that does not change the type of an expression.

Bad Example
const x: number = 3;
const y = x!;
Good Example
const x: number = 3;
const y = x;

Disallows unnecessary constraints on generic types

Rule ID: @typescript-eslint/no-unnecessary-type-constraint

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.

Bad Example
function foo<T extends any>(arg: T) {
return arg;
}
Good Example
function foo<T>(arg: T) {
return arg;
}

Disallow calling a function with a value with type any

Rule ID: @typescript-eslint/no-unsafe-argument

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.

Bad Example
declare function foo(x: number): void;
const a: any = 1;
foo(a);
Good Example
declare function foo(x: number): void;
const a: number = 1;
foo(a);

Disallows assigning any to variables and properties

Rule ID: @typescript-eslint/no-unsafe-assignment

Description: Despite your best intentions, the any type can sometimes leak into your codebase.

Bad Example
const value: any = getData();
const n: number = value;
Good Example
const value: unknown = getData();
const n: number = value as number;

Disallows calling an any type value

Rule ID: @typescript-eslint/no-unsafe-call

Description: Despite your best intentions, the any type can sometimes leak into your codebase.

Bad Example
const fn: any = getFn();
fn();
Good Example
const fn: () => void = getFn();
fn();

Disallow unsafe declaration merging

Rule ID: @typescript-eslint/no-unsafe-declaration-merging

Description: Declaration merging between classes and interfaces is unsafe. The TypeScript compiler doesn't check whether properties are initialized, which can cause lead to TypeScript not detecting code that will cause runtime errors.

Bad Example
interface Foo {
bar(): void;
}
class Foo {}
Good Example
class Foo {
bar(): void {}
}

Disallows member access on any typed variables

Rule ID: @typescript-eslint/no-unsafe-member-access

Description: Despite your best intentions, the any type can sometimes leak into your codebase.

Bad Example
const obj: any = getObj();
const name = obj.name;
Good Example
const obj: { name: string } = getObj();
const name = obj.name;

Disallows returning any from a function

Rule ID: @typescript-eslint/no-unsafe-return

Description: Despite your best intentions, the any type can sometimes leak into your codebase.

Bad Example
function foo(): number {
const x: any = 1;
return x;
}
Good Example
function foo(): number {
const x: number = 1;
return x;
}

Disallow unused expressions

Rule ID: @typescript-eslint/no-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.

Bad Example
declare const a: number;
declare const b: number;
a + b;
Good Example
declare const a: number;
declare const b: number;
const c = a + b;

Disallow unused variables

Rule ID: @typescript-eslint/no-unused-vars

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.

Bad Example
const unused = 42;
console.log("hello");
Good Example
const used = 42;
console.log(used);

Disallow unused variables and arguments

Rule ID: @typescript-eslint/no-unused-vars-experimental

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.

Bad Example
function foo(a: number, b: number) {
return a;
}
Good Example
function foo(a: number) {
return a;
}

Disallow the use of variables before they are defined

Rule ID: @typescript-eslint/no-use-before-define

Description: This rule will warn when it encounters a reference to an identifier that has not yet been declared.

Bad Example
console.log(x);
const x = 1;
Good Example
const x = 1;
console.log(x);

Disallow unnecessary constructors

Rule ID: @typescript-eslint/no-useless-constructor

Description: This rule flags class constructors that can be safely removed without changing how the class works.

Bad Example
class Foo {
constructor() {}
}
Good Example
class Foo {}

Disallow empty exports that don't change anything in a module file

Rule ID: @typescript-eslint/no-useless-empty-export

Description: This rule reports an 'export {}' that doesn't do anything in a file already using ES modules.

Bad Example
export const value = 1;
export {};
Good Example
export const value = 1;

Disallows the use of require statements except in import statements

Rule ID: @typescript-eslint/no-var-requires

Description: In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports.

Bad Example
const foo = require("foo");
Good Example
import foo from "foo";

Prefers a non-null assertion over explicit type cast when possible

Rule ID: @typescript-eslint/non-nullable-type-assertion-style

Description: This rule detects when an as cast is doing the same job as a ! would, and suggests fixing the code to be an !.

Bad Example
declare const x: string | undefined;
const y = x as string;
Good Example
declare const x: string | undefined;
const y = x!;

Enforce consistent spacing inside braces

Rule ID: @typescript-eslint/object-curly-spacing

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

Rule ID: @typescript-eslint/padding-line-between-statements

Description: Require or disallow padding lines between statements.

Require Parameter properties

Rule ID: @typescript-eslint/parameter-properties

Description: Require or disallow parameter properties in class constructors.

Prefer usage of as const over literal type

Rule ID: @typescript-eslint/prefer-as-const

Description: This rule recommends usage of const assertion when type primitive value is equal to type.

Bad Example
let x: 2 = 2;
Good Example
let x = 2 as const;

Prefer initializing each enums member value

Rule ID: @typescript-eslint/prefer-enum-initializers

Description: This rule recommends having each enums member value explicitly initialized.

Bad Example
enum Status {
Open,
Closed,
}
Good Example
enum Status {
Open = 1,
Closed = 2,
}

Prefer a ‘for-of’ loop over a standard ‘for’ loop if the index is only used to access the array being iterated

Rule ID: @typescript-eslint/prefer-for-of

Description: This rule recommends a for-of loop when the loop index is only used to read from an array that is being iterated.

Bad Example
const arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Good Example
const arr = [1, 2, 3];
for (const value of arr) {
console.log(value);
}

Use function types instead of interfaces with call signatures

Rule ID: @typescript-eslint/prefer-function-type

Description: This rule suggests using a function type instead of an interface or object type literal with a single call signature.

Bad Example
interface Callback {
(data: string): void;
}
Good Example
type Callback = (data: string) => void;

Enforce includes method over indexOf method

Rule ID: @typescript-eslint/prefer-includes

Description: Until ES5, we were using String#indexOf method to check whether a string contains an arbitrary substring or not.

Bad Example
declare const str: string;
if (str.indexOf("foo") !== -1) {
}
Good Example
declare const str: string;
if (str.includes("foo")) {
}

Require that all enum members be literal values to prevent unintended enum member name shadow issues

Rule ID: @typescript-eslint/prefer-literal-enum-member

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:

Bad Example
const value = 1;
enum Foo {
A = value,
}
Good Example
enum Foo {
A = 1,
}

Require the use of the namespace keyword instead of the module keyword to declare custom TypeScript modules

Rule ID: @typescript-eslint/prefer-namespace-keyword

Description: In an effort to prevent further confusion between custom TypeScript modules and the new ES2015 modules, starting

Bad Example
module Foo {
export const x = 1;
}
Good Example
namespace Foo {
export const x = 1;
}

Enforce the usage of the nullish coalescing operator instead of logical chaining

Rule ID: @typescript-eslint/prefer-nullish-coalescing

Description: TypeScript 3.7 added support for the nullish coalescing operator.

Bad Example
declare const value: string | null;
const result = value || 'default';
Good Example
declare const value: string | null;
const result = value ?? 'default';

Prefer using concise optional chain expressions instead of chained logical ands

Rule ID: @typescript-eslint/prefer-optional-chain

Description: TypeScript 3.7 added support for the optional chain operator.

Bad Example
declare const foo: { bar?: { baz?: string } } | undefined;
const x = foo && foo.bar && foo.bar.baz;
Good Example
declare const foo: { bar?: { baz?: string } } | undefined;
const x = foo?.bar?.baz;

Requires that private members are marked as readonly if they're never modified outside of the constructor

Rule ID: @typescript-eslint/prefer-readonly

Description: This rule enforces that private members are marked as readonly if they're never modified outside of the constructor.

Bad Example
class C {
private name = 'x';
getName() {
return this.name;
}
}
Good Example
class C {
private readonly name = 'x';
getName() {
return this.name;
}
}

Requires that function parameters are typed as readonly to prevent accidental mutation of inputs

Rule ID: @typescript-eslint/prefer-readonly-parameter-types

Description: Mutating function arguments can lead to confusing, hard to debug behavior.

Bad Example
function total(arr: number[]): number {
return arr.reduce((a, b) => a + b, 0);
}
Good Example
function total(arr: readonly number[]): number {
return arr.reduce((a, b) => a + b, 0);
}

Prefer using type parameter when calling Array#reduce instead of casting

Rule ID: @typescript-eslint/prefer-reduce-type-parameter

Description: It's common to call Array#reduce with a generic type, such as an array or object, as the initial value.

Bad Example
[1, 2, 3].reduce((acc, e) => [...acc, e], [] as number[]);
Good Example
[1, 2, 3].reduce<number[]>((acc, e) => [...acc, e], []);

Enforce that RegExp#exec is used instead of String#match if no global flag is provided

Rule ID: @typescript-eslint/prefer-regexp-exec

Description: RegExp#exec is faster than String#match and both work the same when not using the /g flag.

Bad Example
'hello world'.match(/world/);
Good Example
/world/.exec('hello world');

Proper use of this

Rule ID: @typescript-eslint/prefer-return-this-type

Description: Enforce that this is used when only this type is returned.

Bad Example
class Builder {
setName(): Builder {
return this;
}
}
Good Example
class Builder {
setName(): this {
return this;
}
}

Enforce the use of String#startsWith and String#endsWith instead of other equivalent methods of checking substrings

Rule ID: @typescript-eslint/prefer-string-starts-ends-with

Description: There are multiple ways to verify if a string starts or ends with a specific string, such as foo.indexOf('bar') === 0.

Bad Example
declare const s: string;
const startsWithFoo = s.indexOf('foo') === 0;
Good Example
declare const s: string;
const startsWithFoo = s.startsWith('foo');

Recommends using @ts-expect-error over @ts-ignore

Rule ID: @typescript-eslint/prefer-ts-expect-error

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.

Bad Example
// @ts-ignore
const x: number = 'foo';
Good Example
// @ts-expect-error
const x: number = 'foo';

Requires any function or method that returns a Promise to be marked async

Rule ID: @typescript-eslint/promise-function-async

Description: Requires any function or method that returns a Promise to be marked async.

Bad Example
function getValue() {
return Promise.resolve(1);
}
Good Example
async function getValue() {
return Promise.resolve(1);
}

Enforce the consistent use of either backticks, double, or single quotes

Rule ID: @typescript-eslint/quotes

Description: This rule enforces the consistent use of either backticks, double, or single quotes.

Requires Array#sort calls to always provide a compareFunction

Rule ID: @typescript-eslint/require-array-sort-compare

Description: This rule prevents invoking the Array#sort() method without providing a compare argument.

Bad Example
const nums = [3, 1, 2];
nums.sort();
Good Example
const nums = [3, 1, 2];
nums.sort((a, b) => a - b);

Disallow async functions which have no await expression

Rule ID: @typescript-eslint/require-await

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.

Bad Example
async function getValue() {
return 1;
}
Good Example
async function getValue() {
return await Promise.resolve(1);
}

When adding two variables, operands must both be of type number or of type string

Rule ID: @typescript-eslint/restrict-plus-operands

Description: Examples of correct code:

Bad Example
declare const count: number;
const label = count + '!';
Good Example
declare const count: number;
const label = String(count) + '!';

Enforce template literal expressions to be of string type

Rule ID: @typescript-eslint/restrict-template-expressions

Description: Examples of correct code:

Bad Example
declare const obj: object;
const s = `value: ${obj}`;
Good Example
declare const obj: object;
const s = `value: ${JSON.stringify(obj)}`;

Enforces consistent returning of awaited values

Rule ID: @typescript-eslint/return-await

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).

Bad Example
async function f() {
return await Promise.resolve(1);
}
Good Example
async function f() {
return Promise.resolve(1);
}

Require or disallow semicolons instead of ASI

Rule ID: @typescript-eslint/semi

Description: This rule enforces consistent use of semicolons after statements.

Enforce constituents of a type union/intersection to be sorted alphabetically

Rule ID: @typescript-eslint/sort-type-constituents

Description: This rule reports on any types that aren't sorted alphabetically.

Enforces that members of a type union/intersection are sorted alphabetically

Rule ID: @typescript-eslint/sort-type-union-intersection-members

Description: Sorting union (|) and intersection (&) types can help:

Enforces consistent spacing before function parenthesis

Rule ID: @typescript-eslint/space-before-function-paren

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.

Rule ID: @typescript-eslint/space-infix-ops

Description: This rule extends the base eslint/space-infix-ops rule.

Restricts the types allowed in boolean expressions

Rule ID: @typescript-eslint/strict-boolean-expressions

Description: Forbids usage of non-boolean types in expressions where a boolean is expected.

Bad Example
declare const name: string | null;
if (name) {
console.log(name);
}
Good Example
declare const name: string | null;
if (name != null) {
console.log(name);
}

Exhaustiveness checking in switch with union type

Rule ID: @typescript-eslint/switch-exhaustiveness-check

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.

Bad Example
type T = 'a' | 'b';
declare const t: T;
switch (t) {
case 'a':
break;
}
Good Example
type T = 'a' | 'b';
declare const t: T;
switch (t) {
case 'a':
break;
case 'b':
break;
}

Sets preference level for triple slash directives versus ES6-style import declarations

Rule ID: @typescript-eslint/triple-slash-reference

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.

Bad Example
/// <reference types="node" />
import { readFile } from 'fs';
Good Example
import type {} from 'node';
import { readFile } from 'fs';

Require consistent spacing around type annotations

Rule ID: @typescript-eslint/type-annotation-spacing

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

Rule ID: @typescript-eslint/typedef

Description: TypeScript cannot always infer types for all places in code.

Enforces unbound methods are called with their expected scope

Rule ID: @typescript-eslint/unbound-method

Description: Warns when a method is used outside of a method call.

Bad Example
class C {
x = 1;
getX() {
return this.x;
}
}
const c = new C();
const fn = c.getX;
Good Example
class C {
x = 1;
getX() {
return this.x;
}
}
const c = new C();
const fn = () => c.getX();

Warns for any two overloads that could be unified into one by using a union or an optional/rest parameter

Rule ID: @typescript-eslint/unified-signatures

Description: Warns for any two overloads that could be unified into one by using a union or an optional/rest parameter.

Bad Example
function f(x: number): void;
function f(x: string): void;
function f(x: unknown): void {}
Good Example
function f(x: number | string): void {}

Security

Cyclopt scans your TypeScript code for security vulnerabilities, injection, insecure configuration, weak cryptography, data exposure, and more. Each finding below lists its Rule ID, what it detects and how to fix it, a severity, and the relevant CWE/OWASP classification.

note

Security findings are mapped to industry classifications (CWE and OWASP).


Angular Bypasssecuritytrust

Rule ID: angular-bypasssecuritytrust

Description: Calling Angular DomSanitizer.$TRUST(...) on data that originates from function parameters bypasses Angular's built-in XSS protection and trusts raw HTML, URLs or scripts. Route untrusted values through a sanitizer such as DOMPurify (or sanitizer.sanitize(SecurityContext.HTML, ...)) before passing them to bypassSecurityTrust* APIs.

CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025

Severity Category

AWS Cdk Bucket Enforcessl

Rule ID: aws-cdk-bucket-enforcessl

Description: S3 Bucket construct $X permits cleartext HTTP requests because enforceSSL is not set to true. Clients may then upload or download objects without TLS, exposing data in transit to interception. Set enforceSSL: true in the bucket props (or attach an equivalent deny-non-SSL bucket policy).

CWE: CWE-319 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Awscdk Bucket Encryption

Rule ID: awscdk-bucket-encryption

Description: S3 Bucket construct $X is being created without server-side encryption configured. Objects written to this bucket will be stored unencrypted at rest, leaking sensitive data on disk compromise. Pass encryption: BucketEncryption.S3_MANAGED or BucketEncryption.KMS_MANAGED in the bucket props.

CWE: CWE-311 · OWASP: A03:2017, A04:2021, A06:2025

Severity Category

Awscdk Bucket Grantpublicaccessmethod

Rule ID: awscdk-bucket-grantpublicaccessmethod

Description: Invoking $X.grantPublicAccess(...) on an S3 Bucket construct makes every object in the bucket readable by anyone on the internet without authentication. Unintended public exposure of S3 contents is one of the most common cloud breach vectors. Remove this call and grant access through IAM principals or signed URLs instead.

CWE: CWE-306 · OWASP: A07:2021, A07:2025

Severity Category

Awscdk Codebuild Project Public

Rule ID: awscdk-codebuild-project-public

Description: CodeBuild Project construct $X is configured with badge: true, which publishes its build history, logs and artifacts to an unauthenticated public URL, including builds created before the project was made public. Leaked build logs commonly disclose secrets, source code and internal endpoints. Remove badge: true unless public exposure is an explicit requirement.

CWE: CWE-306 · OWASP: A07:2021, A07:2025

Severity Category

Awscdk Sqs Unencryptedqueue

Rule ID: awscdk-sqs-unencryptedqueue

Description: SQS Queue construct $X is being created without server-side encryption, so message payloads are stored unencrypted at rest in the queue. Add encryption: QueueEncryption.KMS_MANAGED (or QueueEncryption.KMS with a customer-managed key) to the queue props to protect message contents.

CWE: CWE-311 · OWASP: A03:2017, A04:2021, A06:2025

Severity Category

CORS Regex Wildcard

Rule ID: cors-regex-wildcard

Description: The CORS origin allow-list regex $CORS contains an unescaped . in $PATTERN, so attacker-controlled hostnames like evil-yourdomainXcom will match what was intended to be your.domain.com. This lets unintended third-party origins bypass the Same-Origin Policy. Escape the literal dots (\.) and anchor the regex with ^ and $.

CWE: CWE-183 · OWASP: A04:2021, A06:2025

Severity Category

Nestjs Header CORS Any

Rule ID: nestjs-header-cors-any

Description: NestJS is sending Access-Control-Allow-Origin: * via @Header(...), NestFactory.create(..., { cors: true }) or app.enableCors(...) with a wildcard origin, which disables the browser Same-Origin Policy and lets any site read authenticated responses from this API. Restrict origin to an explicit list of trusted domains instead of * or true.

CWE: CWE-183 · OWASP: A04:2021, A06:2025

Severity Category

Nestjs Header XSS Disabled

Rule ID: nestjs-header-xss-disabled

Description: A NestJS handler is emitting X-XSS-Protection: 0 through @Header(...), which explicitly turns off the legacy browser XSS auditor on responses from this route. Prefer either omitting the header entirely (modern default) or sending X-XSS-Protection: 1; mode=block together with a strict Content-Security-Policy.

CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025

Severity Category

Nestjs Open Redirect

Rule ID: nestjs-open-redirect

Description: A NestJS @Redirect(...) handler is returning { url: $URL } with a non-literal value, so request-controlled input can drive the redirect target. Attackers exploit this to send victims to phishing sites under the appearance of your domain. Validate $URL against an allow-list of relative paths or trusted hosts before returning it.

CWE: CWE-601 · OWASP: A01:2021, A01:2025

Severity Category

I18next Key Format

Rule ID: i18next-key-format

Description: The i18next t('$KEY', ...) call uses a translation key that does not follow the project naming convention module.feature.identifier (lowercase, dotted, three or more segments). Inconsistent keys make translation files harder to organise, diff and audit. Rename the key to module.feature.* format.

Severity Category

Jsx Label Not I18n

Rule ID: jsx-label-not-i18n

Description: MUI <TextField> or <Tab> is rendering the hard-coded label="$MESSAGE" string directly in JSX, so the text cannot be translated for other locales. Wrap the label through i18next, e.g. label={t('module.feature.key')}, instead of hard-coding the English copy in the component.

Severity Category

Jsx Not Internationalized

Rule ID: jsx-not-internationalized

Description: A JSX element contains the hard-coded text $MESSAGE as its child instead of a translated value, so this UI string ships in one language only. Replace the inline text with an i18next call such as {t('module.feature.key')} to keep all user-facing copy localizable.

Severity Category

Mui Snackbar Message

Rule ID: mui-snackbar-message

Description: enqueueSnackbar('$MESSAGE', ...) is being called with a literal English string, so notification toasts will not switch language with the rest of the UI. Pass the message through i18next instead, for example enqueueSnackbar(t('module.feature.key'), ...).

Severity Category

React Dangerouslysetinnerhtml

Rule ID: react-dangerouslysetinnerhtml

Description: A React component is feeding a prop or function parameter straight into dangerouslySetInnerHTML={{ __html: ... }}, which renders raw markup and executes any embedded <script> or event handlers as XSS. Sanitize the value with DOMPurify.sanitize(...) (or sanitize-html) before assigning it, or render the data as plain text children instead.

CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025

Severity Category

React Href Var

Rule ID: react-href-var

Description: An anchor element is rendering href={$X} from a component prop or function parameter, allowing an attacker who controls that value to inject a javascript: URI that executes on click as stored XSS. Validate the URL against a strict scheme allow-list (http, https, mailto) or drop unknown protocols before assigning it to href.

CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025

Severity Category

React Insecure Request

Rule ID: react-insecure-request

Description: An axios.$VERB("$URL", ...) or fetch("$URL", ...) call targets a plain http:// URL on a non-loopback host, so request and response bodies (including auth tokens) travel unencrypted and can be intercepted or tampered with on the network path. Switch the URL to https://, or proxy the call through an HTTPS endpoint.

CWE: CWE-319 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

React JWT Decoded Property

Rule ID: react-jwt-decoded-property

Description: Reading $DECODED.$PROPERTY from jwt_decode(...) treats unverified token claims as authoritative; because jwt-decode only base64-decodes the payload and never validates the signature, any client-side authorization decision based on these fields can be forged. Treat decoded claims as informational only and enforce auth on the server with a verified token.

CWE: CWE-922 · OWASP: A01:2021, A01:2025

Severity Category

React JWT In Localstorage

Rule ID: react-jwt-in-localstorage

Description: A JWT (or its decoded form) is being persisted via localStorage.setItem(...), where any successful XSS payload can read the token and impersonate the user. Web Storage has no protection equivalent to HttpOnly cookies. Move the token into a Secure; HttpOnly; SameSite cookie set by the server.

CWE: CWE-922 · OWASP: A01:2021, A01:2025

Severity Category

React Markdown Insecure HTML

Rule ID: react-markdown-insecure-html

Description: A react-markdown component is rendered with allowDangerousHtml, escapeHtml={false} or a custom transformLinkUri / transformImageUri, each of which disables the library's built-in XSS protections and lets raw HTML, javascript: links or untrusted image URIs reach the DOM. Drop these props and rely on react-markdown's default sanitization, or run output through DOMPurify before rendering.

CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025

Severity Category

React Unsanitized Method

Rule ID: react-unsanitized-method

Description: The DOM sink document.$HTML(...) (e.g. document.write, document.writeln or insertAdjacentHTML) is being called with a value derived from a component prop, parsing the argument as live HTML and triggering XSS when that input is attacker-controlled. Sanitize the payload with DOMPurify.sanitize(...) or replace the sink with textContent / createElement + text assignments.

CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025

Severity Category

React Unsanitized Property

Rule ID: react-unsanitized-property

Description: Assigning to .$HTML (innerHTML or outerHTML) on a ref obtained from useRef, createRef or findDOMNode writes raw markup into the DOM, so component-prop input parsed here executes any embedded scripts as XSS. Either sanitize the value through DOMPurify.sanitize(...) first, or set textContent / use React children to render the data safely.

CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025

Severity Category

Useselect Label Not I18n

Rule ID: useselect-label-not-i18n

Description: The useSelect(...) hook is invoked with the hard-coded label '$LABEL' in its third argument, so this dropdown caption stays in one language across locales. Replace the literal with a translated value such as t('module.feature.key') so the label follows the active language.

Severity Category

Ship Fast. Validate Smarter.Protect your reputation.

Cyclopt G2 profile

29A, Ptolemaion Street, Coho Building, Thessaloniki, Greece, Tel: +30 2310 471 030
Copyright © 2026 Cyclopt
We use cookies to improve user experience. For more information you can visit our Privacy policy