noInferrableTypes
Ce contenu n’est pas encore disponible dans votre langue.
Diagnostic Category: lint/style/noInferrableTypes
Since: v1.0.0
Sources:
Disallow type annotations for variables, parameters, and class properties initialized with a literal expression.
TypeScript is able to infer the types of parameters, properties, and variables from their default or initial values.
There is no need to use an explicit :
type annotation for trivially inferred types (boolean, bigint, number, regex, string).
Doing so adds unnecessary verbosity to code making it harder to read.
In contrast to ESLint’s rule, this rule allows to use a wide type for const
declarations.
Moreover, the rule does not recognize undefined
values, primitive type constructors (String, Number, …), and RegExp
type.
These global variables could be shadowed by local ones.
Examples
Section titled ExamplesInvalid
Section titled Invalidcode-block.ts:1:15 lint/style/noInferrableTypes FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This type annotation is trivially inferred from its initialization.
> 1 │ const variable: 1 = 1;
│ ^^^
2 │
ℹ Safe fix: Remove the type annotation.
1 │ - const·variable:·1·=·1;
1 │ + const·variable·=·1;
2 2 │
code-block.ts:1:13 lint/style/noInferrableTypes FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This type annotation is trivially inferred from its initialization.
> 1 │ let variable: number = 1;
│ ^^^^^^^^
2 │
ℹ Safe fix: Remove the type annotation.
1 │ - let·variable:·number·=·1;
1 │ + let·variable·=·1;
2 2 │
code-block.ts:2:17 lint/style/noInferrableTypes FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This type annotation is trivially inferred from its initialization.
1 │ class SomeClass {
> 2 │ readonly field: 1 = 1;
│ ^^^
3 │ }
4 │
ℹ Safe fix: Remove the type annotation.
1 1 │ class SomeClass {
2 │ - ··readonly·field:·1·=·1;
2 │ + ··readonly·field·=·1;
3 3 │ }
4 4 │
code-block.ts:2:8 lint/style/noInferrableTypes FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This type annotation is trivially inferred from its initialization.
1 │ class SomeClass {
> 2 │ field: number = 1;
│ ^^^^^^^^
3 │ }
4 │
ℹ Safe fix: Remove the type annotation.
1 1 │ class SomeClass {
2 │ - ··field:·number·=·1;
2 │ + ··field·=·1;
3 3 │ }
4 4 │
code-block.ts:1:17 lint/style/noInferrableTypes FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This type annotation is trivially inferred from its initialization.
> 1 │ function f(param: number = 1): void {}
│ ^^^^^^^^
2 │
ℹ Safe fix: Remove the type annotation.
1 │ - function·f(param:·number·=·1):·void·{}
1 │ + function·f(param·=·1):·void·{}
2 2 │