- 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.
- Rust實戰
- 秒懂設計模式
- Python貝葉斯分析(第2版)
- 深入淺出Serverless:技術原理與應用實踐
- Tableau 10 Bootcamp
- Node.js區塊鏈開發
- Python機器學習與量化投資
- Learning Concurrency in Python
- WordPress Search Engine Optimization(Second Edition)
- Hadoop Blueprints
- Zend Framework 2 Cookbook
- C語言從入門到精通(微視頻精編版)
- Neo4j權威指南 (圖數據庫技術叢書)
- C語言解惑:指針、數組、函數和多文件編程
- Unreal Engine 4 Game Development Essentials