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

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.

主站蜘蛛池模板: 延边| 霍州市| 仲巴县| 元谋县| 彭泽县| 富阳市| 宜宾县| 科技| 莱芜市| 宜良县| 镇康县| 迁西县| 兖州市| 岳阳县| 昭觉县| 吉木乃县| 郓城县| 盐津县| 和平区| 镇江市| 福建省| 上饶县| 上饶县| 伊金霍洛旗| 阳东县| 华安县| 巩义市| 五莲县| 湘潭市| 汕头市| 丰都县| 武穴市| 盐城市| 绥中县| 连云港市| 五寨县| 铅山县| 昭苏县| 江陵县| 东辽县| 云安县|