Static typing has a number of benefits; however, it makes us write a more verbose code by adding all the type annotations.
In some cases, the TypeScript's compiler is able to guess the types of expressions inside our code; let's consider this example, for instance:
let answer = 42; answer = '42'; // Type "string" is not assignable to type "number"
In the preceding example, we defined a variable answer
and assigned the value 42
to it. Since TypeScript is statically typed and the type of a variable cannot change once declared, the compiler is smart enough to guess that the type of answer
is number
.
If we don't assign a value to a variable within its definition, the compiler will set its type to any
:
let answer; answer = 42; answer = '42';
The preceding snippet will compile without any compile-time errors.