noBannedTypes
Diagnostic Category: lint/complexity/noBannedTypes
Since: v1.0.0
Sources:
- Same as:
@typescript-eslint/ban-types
Disallow primitive type aliases and misleading types.
- Enforce consistent names for primitive types
Primitive types have aliases.
For example, Number
is an alias of number
.
The rule recommends the lowercase primitive type names.
- Disallow the
Function
type
The Function
type is loosely typed and is thus considered dangerous or harmful.
Function
is equivalent to the type (...rest: any[]) => any
that uses the unsafe any
type.
- Disallow the misleading non-nullable type
{}
In TypeScript, the type {}
doesn’t represent an empty object.
It represents any value except null
and undefined
.
The following TypeScript example is perfectly valid:
code-block.ts:1:10 lint/complexity/noBannedTypes ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Don’t use ’{}’ as a type.
> 1 │ const n: {} = 0
│ ^^
2 │
ℹ Prefer explicitly define the object shape. ’{}’ means “any non-nullable value”.
To represent an empty object, you should use { [k: string]: never }
or Record<string, never>
.
To avoid any confusion, the rule forbids the use of the type {}
, except in two situations:
- In type constraints to restrict a generic type to non-nullable types:
- In a type intersection to narrow a type to its non-nullable equivalent type:
In this last case, you can also use the NonNullable
utility type:
Examples
Section titled ExamplesInvalid
Section titled Invalidcode-block.ts:1:10 lint/complexity/noBannedTypes FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Don’t use ‘String’ as a type.
> 1 │ let foo: String = “bar”;
│ ^^^^^^
2 │
ℹ Use lowercase primitives for consistency.
ℹ Safe fix: Use ‘string’ instead
1 │ - let·foo:·String·=·“bar”;
1 │ + let·foo:·string·=·“bar”;
2 2 │
code-block.ts:1:20 lint/complexity/noBannedTypes FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Don’t use ‘Boolean’ as a type.
> 1 │ let bool = true as Boolean;
│ ^^^^^^^
2 │
ℹ Use lowercase primitives for consistency.
ℹ Safe fix: Use ‘boolean’ instead
1 │ - let·bool·=·true·as·Boolean;
1 │ + let·bool·=·true·as·boolean;
2 2 │
code-block.ts:1:28 lint/complexity/noBannedTypes FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Don’t use ‘Boolean’ as a type.
> 1 │ let invalidTuple: [string, Boolean] = [“foo”, false];
│ ^^^^^^^
2 │
ℹ Use lowercase primitives for consistency.
ℹ Safe fix: Use ‘boolean’ instead
1 │ - let·invalidTuple:·[string,·Boolean]·=·[“foo”,·false];
1 │ + let·invalidTuple:·[string,·boolean]·=·[“foo”,·false];
2 2 │