Reader small image

You're reading from  Getting Started with Angular - Second edition - Second Edition

Product typeBook
Published inFeb 2017
Reading LevelIntermediate
PublisherPackt
ISBN-139781787125278
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Minko Gechev
Minko Gechev
author image
Minko Gechev

Minko Gechev is a software engineer who strongly believes in open source software. He has developed numerous such projects including codelyzer, the AngularJS style guide, aspect.js and many others, and is one of the coauthors of the official Angular style guide.
Read more about Minko Gechev

Right arrow

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 to any:

let answer; 
answer = 42; 
answer = '42'; 

The preceding snippet will compile without any compile-time errors.

Best common type

Sometimes, the type inference could be a result of several expressions. Such is the case...

lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Getting Started with Angular - Second edition - Second Edition
Published in: Feb 2017Publisher: PacktISBN-13: 9781787125278

Author (1)

author image
Minko Gechev

Minko Gechev is a software engineer who strongly believes in open source software. He has developed numerous such projects including codelyzer, the AngularJS style guide, aspect.js and many others, and is one of the coauthors of the official Angular style guide.
Read more about Minko Gechev