Book Image

Getting Started with Angular - Second edition - Second Edition

By : Minko Gechev
Book Image

Getting Started with Angular - Second edition - Second Edition

By: Minko Gechev

Overview of this book

Want to build quick and robust web applications with Angular? This book is the quickest way to get to grips with Angular and take advantage of all its new features.
Table of Contents (16 chapters)
Getting Started with Angular Second Edition
Credits
Foreword
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

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...