Variables in TypeScript are implicitly typed based on their initial assignment (Learn more). For example, both variables below are automatically typed as boolean
:
let a = true; // implicitly typed as boolean
let b: boolean = true; // explicitly typed as boolean
If you try to assign a different type to these variables, you will encounter an error:
a = "a string"; // error, type 'string' is not assignable to type 'boolean'
b = "a string"; // error, type 'string' is not assignable to type 'boolean'
There's no strict convention on whether to be explicit or implicit, but it's generally recommended to opt for brevity. For instance, using let a = true;
can be clearer than let a: boolean = true;
. The value assigned already indicates the type, so repeating it may not be necessary.
Avoiding Implicit 'any' Types
Be cautious of unintentionally creating "implicit any types". This happens when a variable lacks an initial assignment and type specification:
let a; // implicitly typed as `any`
Such variables can accept values of any type:
a = true; // valid
a = "a string"; // valid
To prevent this, specify the type explicitly:
let a: boolean;
a = true; // valid
a = "a string"; // error, type 'string' is not assignable to type 'boolean' -- good!
To completely eliminate accidental implicit 'any' types, consider enabling the compiler option --noImplicitAny
, which triggers a compile error when such instances occur. It's advisable to activate this setting.
let a; // compile error with `--noImplicitAny`