The Basic
问题
JavaScript 只提供了动态类型,只有在运行时才能知道发生了什么错误。 使用静态的类型系统,在代码实际执行前预测代码的行为。
Static type-checking
静态类型检查: 添加一些类型代码,find bugs before our code runs
简单的研发流程: 设计、实现、测试、上线;bug 越是在后面流程发现,损失越大
Non-exception Failures
Types for Tooling
tsc
, the TypeScript compiler
tsc
: TypeScript编译器
bash
# 安装
$ npm install -g typescript
# hello.ts
$ echo "console.log('Hello world!');" > hello.ts
# 编译
$ tsc hello.ts # 生成 hello.js
类型检查,hello.ts
ts
// This is an industrial-grade general-purpose greeter function:
function greet(person, date) {
console.log(`Hello ${person}, today is ${date}!`);
}
greet('Brendan'); // Error: Expected 2 arguments, but got 1.
编译报错
bash
$ tsc hello.ts
Expected 2 arguments, but got 1.
Emitting with Errors
报错时仍产出文件
Explicit Types
ts
function greet(person: string, date: Date) {
console.log(`Hello ${person}, today is ${date.toDateString()}!`);
}
// 参数类型检查
greet('Maddison', new Date());
// 类型推断
let msg = 'hello there!'; // string
Erased Types
ts编译成 js 之后,类型会被擦除掉; hello.js
文件:
ts
'use strict';
function greet(person, date) {
console.log('Hello '.concat(person, ', today is ').concat(date.toDateString(), '!'));
}
greet('Maddison', new Date());
Note: 类型注解永远不会改变你的程序在运行时的行为
Downleveling
// TODO
Strictness
类型检查器严格性
不同的用户会由于不同的理由去选择使用 TypeScript 的类型检查器。 CLI 中的 strict 配置项,或者 tsconfig.json 中的 "strict: true" 配置项,可以一次性开启全部严格性设置。但我们也可以单独开启或者关闭某个设置。
需要关注的设置选项:
noImplicitAny
strictNullChecks
noImplicitAny
启用 noImplicitAny
配置项,在遇到被隐式推断为 any 类型的变量时就会抛出一个错误。
strictNullChecks
启用 strictNullChecks
配置项,必须检查 null 和 undefined 的变量。使用更加安全