43 lines
1.3 KiB
Plaintext

== Why is this an issue?
TypeScript supports type inference, a mechanism that automatically infers the type of a variable based on its initial value. This means that if you initialize a variable with a particular value, TypeScript will assume that this variable should always hold that type of value.
Unnecessarily verbose declarations and initializations make it harder to read the code and should be simplified. Therefore, type annotations should be omitted from variable and parameter declarations when they can be easily inferred from the initialized or defaulted value.
== How to fix it
Omit explicit type annotations in declarations whenever the type can be inferred from the context.
=== Code examples
==== Noncompliant code example
[source,javascript,diff-id=1,diff-type=noncompliant]
----
const n: number = 1; // Noncompliant, "number" can be omitted
function foo(s: string = "") {} // Noncompliant, "string" can be omitted
class Bar {
b: boolean = true; // Noncompliant, "boolean" can be omitted
}
----
==== Compliant solution
[source,javascript,diff-id=1,diff-type=compliant]
----
const n = 1;
function foo(s = "") {}
class Bar {
b = true;
}
----
== Resources
=== Documentation
* TypeScript Documentation - https://www.typescriptlang.org/docs/handbook/type-inference.html[Type Inference]