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.
Sometimes, the type inference could be a result of several expressions. Such is the case when we assign a heterogeneous array to a variable:
let x = ['42', 42];
In this case, the type of x
will be any[]
. However, suppose we have the following:
let x = [42, null, 32];
The type of x
will then be number[]
since the type Number
is a subtype of Null
.
Contextual typing occurs when the type of an expression is implied from its location; let's take this example:
document.body.addEventListener('mousedown', e => { e.foo(); // Property "foo" does not exists on a type "MouseEvent" }, false);
In this case, the type of the argument of the callback e
is guessed by the compiler based on the context in which it is used. The compiler understands that the type of e
is based on the call of addEventListener
and the arguments passed to the method. In case we were using a keyboard event (keydown
, for example), TypeScript would have been aware that e
is of the type KeyboardEvent
.
Type inference is a mechanism that allows us to write less verbose code by taking advantage of the static analysis performed by TypeScript. Based on the context, TypeScript's compiler is able to guess the type of a given expression without explicit definition.