官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 丰原市| 漯河市| 黔东| 南岸区| 灵台县| 那曲县| 兖州市| 莲花县| 磐石市| 东辽县| 噶尔县| 班戈县| 康平县| 登封市| 红桥区| 宝兴县| 文水县| 民勤县| 海林市| 潢川县| 班戈县| 鸡西市| 虞城县| 威远县| 蓬莱市| 石台县| 金湖县| 揭东县| 八宿县| 濉溪县| 钟祥市| 新郑市| 莎车县| 湟中县| 德保县| 从化市| 庆安县| 屏东市| 平凉市| 开封县| 杭锦后旗|