TypeScript,转自legacy的gitbook
安装编译
1 | npm install -g typescript |
tsc 对类型做静态检查,如果有错误,编译会报错,但会继续生成编译结果
基础
- 原始数据类型
- 布尔值
1 | let isDone: boolean = false; |
- null类型 和 undefined类型,他俩是所有类型的子类型,即可以赋值给其他类型
1 | let u: undefined = undefined; |
- 数值
1 | let decLiteral: number = 6; |
- 字符串
1 | let myName: string = 'Tom'; |
- 空值, 用于函数返回值
1 | function alertName(): void { |
- 任意类型
1 | let myFavoriteNumber: string = 'seven'; |
- 联合类型
1 | let myFavoriteNumber: string | number; |
- 对象的类型
- 接口
1 | interface Person { |
- 可选属性,带?
1 | interface Person { |
- 任意属性
1 | interface Person { |
使用 [propName: string] 定义了任意属性取 string 类型的值。
需要注意的是,一旦定义了任意属性,那么确定属性和可选属性都必须是它的子属性
- 只读属性
1 | interface Person { |
上例中,使用 readonly 定义的属性 id 初始化后,又被赋值了,所以报错了。
注意,只读的约束存在于第一次给对象赋值的时候,而不是第一次给只读属性赋值的时候
- 数组类型
- 基本数组
1 | let fibonacci: number[] = [1, 1, 2, 3, 5]; |
- 泛型数组
1 | let fibonacci: Array<number> = [1, 1, 2, 3, 5]; |
- 函数类型
1 | // 函数声明(Function Declaration) |
- 类型断言
1 | function getLength(something: string | number): number { |
- 声明文件
1 | // jQuery.d.ts |
- 内置对象
ECMAScript内置对象,在typescript核心库中已经定义好了,还扩展了内置对象,如DOM、BOM等
其他第三方,如node,可以用npm来生成
1 | npm install @types/node --save-dev |
进阶
- 类型别名,关键词type
1 | type Name = string; |
- 字符串字面量类型,关键词type
1 | type EventNames = 'click' | 'scroll' | 'mousemove'; |
- 元组,数组合并了相同类型的对象,而元组(Tuple)合并了不同类型的对象。
1 | let xcatliu: [string, number]; |
越界的元素,当赋值给越界的元素时,它类型会被限制为元组中每个类型的联合类型:
1 | let xcatliu: [string, number]; |
- 枚举,关键词enum
- 普通枚举
枚举成员会被赋值为从 0 开始递增的数字,同时也会对枚举值到枚举名进行反向映射:
1 | enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; |
- 常数枚举
1 | const enum Directions { |
- 继承
使用 extends 关键字实现继承,子类中使用 super 关键字来调用父类的构造函数和方法。
1 | class Cat extends Animal { |
- 存取器
使用 getter 和 setter 可以改变属性的赋值和读取行为:
1 | class Animal { |
- 静态方法
使用 static 修饰符修饰的方法称为静态方法,它们不需要实例化,而是直接通过类来调用:
1 | class Animal { |
public private 和 protected
抽象类
abstract 用于定义抽象类和其中的抽象方法。
抽象类是不允许被实例化的;抽象类中的抽象方法必须被子类实现
1 | abstract class Animal { |
- 类与接口
- 类继承接口
1 | interface Alarm { |
- 类继承多个接口
1 | interface Alarm { |
- 接口继承接口
1 | interface Alarm { |
- 接口继承类
1 | class Point { |
- 混合类型
1 | interface SearchFunc { |
- namespace,之前叫module,内部使用export导出,引入的时候用全名或者import成别名