Optional static type annotations

TypeScript allows us to use type annotations to overcome the scenarios in which the type inference system is not powerful enough to automatically detect the type of a variable.

Let's consider the add function one more time:

function add(a, b) {  return a + b;}

The type of the function add is inferred as the following type:

(a: any, b: any) => any;

The preceding type is a problem because the usage of the any type effectively prevents the TypeScript compiler from detecting certain errors. For example, we might expect the add function to add two numbers:

let result1 = add(2, 3); // 5

However, if we pass a string as input, we will encounter an unexpected result:

let result2 = add("2", 3); // "23"

The preceding ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.