- TypeScript Blueprints
- Ivo Gabe de Wolff
- 384字
- 2021-07-14 10:59:27
Type checking
The compiler will check the types of your code. It has several primitive types and you can define new types yourself. Based on these types, the compiler will warn when a value of a type is used in an invalid manner. That could be using a string for multiplication or using a property of an object that does not exist. The following code would show these errors:
let x = "foo"; x * 2; x.bar();
TypeScript has a special type, called any
, that allows everything; you can assign every value to it and you will never get type errors. The type any
can be used if you do not have an exact type (yet
), for instance, because it is a complex type or if it is from a library that was not written in TypeScript. This means that the following code gives no compile errors:
let x: any = "foo"; x * 2; x.bar();
In the next sections, we will discover these types and learn how the compiler finds these types.
Primitive types
TypeScript has several primitive types, which are listed in the following table:

Defining types
You can define your own types in various ways:

Undefined and null
By default, undefined
and null
can be assigned to every type. Thus, the compiler cannot give you a warning when a value can possibly be undefined or null. TypeScript 2.0 has introduced a new mode, called strictNullChecks
, which adds two new types: undefined
and null
. With that mode, you do get warnings in such cases. We will discover that mode in Chapter 6, Advanced Programming in TypeScript.
Type annotations
TypeScript can infer some types. This means that the TypeScript compiler knows the type, without a type annotation. If a type cannot be inferred, it will default to any
. In such a case, or in case the inferred type is not correct, you have to specify the types yourself. The common declarations that you can annotate are given in the following table:

You can set the compiler option noImplicitAny
to get compiler errors when a type could not be inferred and falls back to any
. It is advised to use that option always, unless you are migrating a JavaScript codebase to TypeScript. You can read about such migration in Chapter 10,Migrate JavaScript to TypeScript.
- The Complete Rust Programming Reference Guide
- Learning NServiceBus(Second Edition)
- vSphere High Performance Cookbook
- 算法大爆炸:面試通關(guān)步步為營
- OpenNI Cookbook
- Visual C#.NET程序設(shè)計
- Node.js全程實例
- Access 2010數(shù)據(jù)庫應(yīng)用技術(shù)實驗指導(dǎo)與習(xí)題選解(第2版)
- Java EE 8 and Angular
- Java程序設(shè)計教程
- Professional JavaScript
- 信息學(xué)奧林匹克競賽初賽精講精練
- Office VBA開發(fā)經(jīng)典:中級進階卷
- JSP大學(xué)實用教程
- Boost.Asio C++ Network Programming Cookbook