Writing less verbose code with TypeScript's type inference
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 ...
Get Getting Started with Angular - 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.