# TypeScript
# 特性
# 类型系统
- 静态类型
- 弱类型(允许隐式类型转换)
# 适用于任何规模
# 与标准同步发展
# 基础
# 原始数据类型
# boolean
let isDone: boolean = false;
// new Boolean() 返回的是Boolean对象
let createdByNewBoolean: Boolean = new Boolean(1);
// 返回boolean类型
let createdByBoolean: boolean = Boolean(1);
2
3
4
5
6
7
8
# number
let decLiteral: number = 6;
// 十六进制
let hexLiteral: number = 0xf00d;
// ES6 中的二进制表示法
let binaryLiteral: number = 0b1010;
// ES6 中的八进制表示法
let octalLiteral: number = 0o744;
let notANumber: number = NaN;
let infinityNumber: number = Infinity;
2
3
4
5
6
7
8
9
# string
let myName: string = 'Tom';
# void
JavaScript 没有空值(Void)的概念,在 TypeScript 中,可以用 void 表示没有任何返回值的函数
function alertName(): void {
alert('My name is Tom');
}
2
3
# Null 和 Undefined
let u: undefined = undefined;
let n: null = null;
2
# 任意值
任意值(Any)用来表示允许赋值为任意类型。
# 任意值的属性和方法
在任意值上访问任何属性都是允许,也允许调用任何方法。
# 类型推论
如果没有明确的指定类型,那么 TypeScript 会依照类型推论(Type Inference)的规则推断出一个类型。
例如一下代码虽然没有指定类型,但是会在编译的时候报错:
let myFavoriteNumber = 'seven';
myFavoriteNumber = 7;
// index.ts(2,1): error TS2322: Type 'number' is not assignable to type 'string'.
2
3
4
如果定义的时候没有赋值,不管之后有没有赋值,都会被推断成 any 类型而完全不被类型检查
let myFavoriteNumber;
myFavoriteNumber = 'seven';
myFavoriteNumber = 7;
2
3
# 联合类型
表示可以取多种类型中的一个
let myFavoriteNumber: string | number;
myFavoriteNumber = 'seven';
myFavoriteNumber = 7;
2
3
当 TypeScript 不确定一个联合类型的变量到底是哪个类型的时候,我们只能访问此联合类型的所有类型里共有的属性或方法
function getLength(something: string | number): number {
return something.length;
}
// index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'.
// Property 'length' does not exist on type 'number'.
2
3
4
5
6
上例中,length 不是 string 和 number 的共有属性,所以会报错。
# 对象的类型-interface
interface是对行为的抽象,具体行动需要类去实现。
interface可用于对类的一部分行为进行抽象以外,也常用于对 对象的形状进行描述。
interface Person {
name: string;
age: number;
}
let tom: Person = {
name: 'Tom',
age: 25
};
2
3
4
5
6
7
8
9
接口一般首字母大写。有的编程语言中会建议接口的名称加上 I 前缀。
定义的变量比接口少或多了一些属性是不允许的,赋值的时候,变量的形状必须和接口的形状保持一致。
# 可选属性
可选属性的含义是该属性可以不存在,仍不允许添加未定义的属性。
interface Person {
name: string;
age?: number;
}
let tom: Person = {
name: 'Tom'
};
2
3
4
5
6
7
8
# 任意属性
interface Person {
name: string;
age?: number;
[propName: string]: any;
}
let tom: Person = {
name: 'Tom',
gender: 'male'
};
2
3
4
5
6
7
8
9
10
一旦定义了任意属性,那么确定属性和可选属性的类型都必须是它的类型的子集:
interface Person {
name: string;
age?: number;
[propName: string]: string;
}
let tom: Person = {
name: 'Tom',
age: 25,
gender: 'male'
};
// index.ts(3,5): error TS2411: Property 'age' of type 'number' is not assignable to string index type 'string'.
// index.ts(7,5): error TS2322: Type '{ [x: string]: string | number; name: string; age: number; gender: string; }' is not assignable to type 'Person'.
// Index signatures are incompatible.
// Type 'string | number' is not assignable to type 'string'.
// Type 'number' is not assignable to type 'string'.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
上例中,任意属性的值允许是 string,但是可选属性 age 的值却是 number,number 不是 string 的子属性,所以报错了。
一个接口中只能定义一个任意属性。
如果接口中有多个类型的属性,则可以在任意属性中使用联合类型:
interface Person {
name: string;
age?: number;
[propName: string]: string | number;
}
let tom: Person = {
name: 'Tom',
age: 25,
gender: 'male'
};
2
3
4
5
6
7
8
9
10
11
# 只读属性
对象中的一些字段只能在创建的时候被赋值,那么可以用 readonly 定义只读属性:
interface Person {
readonly id: number;
name: string;
age?: number;
[propName: string]: any;
}
let tom: Person = {
id: 89757,
name: 'Tom',
gender: 'male'
};
tom.id = 9527;
// index.ts(14,5): error TS2540: Cannot assign to 'id' because it is a constant or a read-only property.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 数组的类型
# 类型 + 方括号
let fibonacci: number[] = [1, 1, 2, 3, 5];
# 数组泛型
let fibonacci: Array<number> = [1, 1, 2, 3, 5];
# 用接口表示
常用来表示类数组。
# 类数组
类数组(Array-like Object)不是数组类型,比如 arguments:
function sum() {
let args: {
[index: number]: number;
length: number;
callee: Function;
} = arguments;
}
2
3
4
5
6
7
事实上常用的类数组都有自己的接口定义,如 IArguments, NodeList, HTMLCollection 等:
function sum() {
let args: IArguments = arguments;
}
2
3
其中 IArguments 是 TypeScript 中定义好了的类型,它实际上就是:
interface IArguments {
[index: number]: any;
length: number;
callee: Function;
}
2
3
4
5
# 函数的类型
# 函数声明
在TS中,要对函数的输入输出都进行类型定义
function sum(x: number, y: number): number {
return x + y;
}
2
3
输入多余或者少于定义的参数是不被允许的。
# 函数表达式
let mySum: (x: number, y: number) => number = function (x: number, y: number): number {
return x + y;
};
2
3
# 用接口定义函数的形状
interface myFunc{
(name:string,age:number):string;
}
let showDetail:myFunc;
showDetail = function(name:string,age:number) {
return name + age
}
2
3
4
5
6
7
# 可选参数
用 ?表示可选参数,可选参数必须接在必需参数后面。可选参数后面不允许再出现必需参数。
function buildName(firstName: string, lastName?: string) {
if (lastName) {
return firstName + ' ' + lastName;
} else {
return firstName;
}
}
let tomcat = buildName('Tom', 'Cat');
let tom = buildName('Tom');
2
3
4
5
6
7
8
9
# 参数默认值
在ES6中,我们允许给函数的参数添加默认值,TS会将添加了默认值的参数识别为可选参数
function buildName(firstName: string, lastName: string = 'Cat') {
return firstName + ' ' + lastName;
}
let tomcat = buildName('Tom', 'Cat');
let tom = buildName('Tom');
2
3
4
5
此时不受 可选参数必须接在必需参数后面 的限制。
function buildName(firstName: string = 'Tom', lastName: string) {
return firstName + ' ' + lastName;
}
let tomcat = buildName('Tom', 'Cat');
let cat = buildName(undefined, 'Cat');
2
3
4
5
# 剩余参数
ES6中可以用...的方式获取函数中的剩余参数。
function push(array: any[], ...items: any[]) {
items.forEach(function(item) {
array.push(item);
});
}
let a = [];
push(a, 1, 2, 3);
2
3
4
5
6
7
剩余参数只能是最后一个参数。
# 重载
重载允许一个函数接受不同数量或类型的参数时,做出不同的处理。
function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string | void {
if (typeof x === 'number') {
return Number(x.toString().split('').reverse().join(''));
} else if (typeof x === 'string') {
return x.split('').reverse().join('');
}
}
2
3
4
5
6
7
8
9
# 类型断言
可以用来手动指定一个值的类型。
值 as 类型
或
<类型>值
# 用途
# 将一个联合类型断言为其中一个类型
当 TypeScript 不确定一个联合类型的变量到底是哪个类型的时候,我们只能访问此联合类型的所有类型中共有的属性或方法
而有时候,我们确实需要在还不确定类型的时候就访问其中一个类型特有的属性或方法,比如:
interface Cat {
name: string;
run(): void;
}
interface Fish {
name: string;
swim(): void;
}
function isFish(animal: Cat | Fish) {
if (typeof animal.swim === 'function') {
return true;
}
return false;
}
// index.ts:11:23 - error TS2339: Property 'swim' does not exist on type 'Cat | Fish'.
// Property 'swim' does not exist on type 'Cat'.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
面的例子中,获取 animal.swim 的时候会报错。
此时可以使用类型断言,将 animal 断言成 Fish:
interface Cat {
name: string;
run(): void;
}
interface Fish {
name: string;
swim(): void;
}
function isFish(animal: Cat | Fish) {
if (typeof (animal as Fish).swim === 'function') {
return true;
}
return false;
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 将一个父类断言为更加具体的子类
class ApiError extends Error {
code: number = 0;
}
class HttpError extends Error {
statusCode: number = 200;
}
function isApiError(error: Error) {
if (typeof (error as ApiError).code === 'number') {
return true;
}
return false;
}
2
3
4
5
6
7
8
9
10
11
12
13
此例子更适合用instanceof
class ApiError extends Error {
code: number = 0;
}
class HttpError extends Error {
statusCode: number = 200;
}
function isApiError(error: Error) {
if (error instanceof ApiError) {
return true;
}
return false;
}
2
3
4
5
6
7
8
9
10
11
12
13
但是如果ApiError和HttpError只是一个接口,接口是一个类型,不是一个真正的值,它在编译结果中会被删除,所以不能使用instanceof来做运行时判断
interface ApiError extends Error {
code: number;
}
interface HttpError extends Error {
statusCode: number;
}
function isApiError(error: Error) {
if (error instanceof ApiError) {
return true;
}
return false;
}
// index.ts:9:26 - error TS2693: 'ApiError' only refers to a type, but is being used as a value here.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
此时只能用类型断言
interface ApiError extends Error {
code: number;
}
interface HttpError extends Error {
statusCode: number;
}
function isApiError(error: Error) {
if (typeof (error as ApiError).code === 'number') {
return true;
}
return false;
}
2
3
4
5
6
7
8
9
10
11
12
13
# 将任何一个类型断言为any
如果我们要在window对象上添加一个属性foo,但ts编译时会报错,提示我们window上不存在foo属性,此时我们可以使用as any临时将window断言为any类型
(window as any).foo = 1;
需要注意的是,将一个变量断言为 any 可以说是解决 TypeScript 中类型问题的最后一个手段。
它极有可能掩盖了真正的类型错误,所以如果不是非常确定,就不要使用 as any。
总之,一方面不能滥用 as any,另一方面也不要完全否定它的作用,我们需要在类型的严格性和开发的便利性之间掌握平衡(这也是 TypeScript 的设计理念之一),才能发挥出 TypeScript 最大的价值。
# 将 any 断言为一个具体的类型
在日常的开发中,我们不可避免的需要处理 any 类型的变量,遇到 any 类型的变量时,我们可以选择改进它,通过类型断言及时的把 any 断言为精确的类型,亡羊补牢,使我们的代码向着高可维护性的目标发展。
举例来说,历史遗留的代码中有个 getCacheData,它的返回值是 any:
function getCacheData(key: string): any {
return (window as any).cache[key];
}
2
3
那么我们在使用它时,最好能够将调用了它之后的返回值断言成一个精确的类型,这样就方便了后续的操作
function getCacheData(key: string): any {
return (window as any).cache[key];
}
interface Cat {
name: string;
run(): void;
}
const tom = getCacheData('tom') as Cat;
tom.run();
2
3
4
5
6
7
8
9
10
11
# 类型断言 vs 类型转换
类型断言只会影响 TypeScript 编译时的类型,类型断言语句在编译结果中会被删除
function toBoolean(something: any): boolean {
return something as boolean;
}
toBoolean(1);
// 返回值为 1
2
3
4
5
6
在上面的例子中,将 something 断言为 boolean 虽然可以通过编译,但是并没有什么用,代码在编译后会变成
function toBoolean(something) {
return something;
}
toBoolean(1);
2
3
4
5
若要进行类型转换,需要直接调用类型转换的方法
function toBoolean(something: any): boolean {
return Boolean(something);
}
toBoolean(1);
2
3
4
5
# 类型断言 vs 类型声明
function getCacheData(key: string): any {
return (window as any).cache[key];
}
interface Cat {
name: string;
run(): void;
}
const tom = getCacheData('tom') as Cat;
tom.run();
2
3
4
5
6
7
8
9
10
11
我们使用 as Cat 将 any 类型断言为了 Cat 类型
function getCacheData(key: string): any {
return (window as any).cache[key];
}
interface Cat {
name: string;
run(): void;
}
const tom: Cat = getCacheData('tom');
tom.run();
2
3
4
5
6
7
8
9
10
11
上面的例子中,我们通过类型声明的方式,将 tom 声明为 Cat,然后再将 any 类型的 getCacheData('tom') 赋值给 Cat 类型的 tom。
它们的区别,可以通过这个例子来理解:
interface Animal {
name: string;
}
interface Cat {
name: string;
run(): void;
}
const animal: Animal = {
name: 'tom'
};
let tom = animal as Cat;
2
3
4
5
6
7
8
9
10
11
12
但是如果将tom声明为cat类型 赋值animal则会报错
let tom: Cat = animal;
// index.ts:12:5 - error TS2741: Property 'run' is missing in type 'Animal' but required in type 'Cat'.
2
类型声明是比类型断言更加严格的。
# 类型断言 vs 泛型
function getCacheData(key: string): any {
return (window as any).cache[key];
}
interface Cat {
name: string;
run(): void;
}
const tom = getCacheData('tom') as Cat;
tom.run();
2
3
4
5
6
7
8
9
10
11
可以用泛型来代替:
function getCacheData<T>(key:string):T {
return (window as any).cache[key];
}
interface Cat {
name: string;
run(): void;
}
const tom = getCacheData<Cat>('tom');
tom.run();
2
3
4
5
6
7
8
9
10
11
通过给 getCacheData 函数添加了一个泛型 <T>,我们可以更加规范的实现对 getCacheData 返回值的约束,这也同时去除掉了代码中的 any,是最优的一个解决方案。
# 声明文件
当使用第三方库时,我们需要引用它的声明文件,才能获得对应的代码补全、接口提示等功能。
declare var声明全局变量declare function声明全局方法declare class声明全局类declare enum声明全局枚举类型declare namespace声明(含有子属性的)全局对象interface和type声明全局类型export导出变量export namespace导出(含有子属性的)对象export defaultES6 默认导出export =commonjs 导出模块export as namespaceUMD 库声明全局变量declare global扩展全局变量declare module扩展模块///三斜线指令
# 什么是声明语句
假如我们想使用第三方库 jQuery,一种常见的方式是在 html 中通过 <script> 标签引入 jQuery,然后就可以使用全局变量 $ 或 jQuery 了。
但是在 ts 中,编译器并不知道 $ 或 jQuery 是什么东西
这时,我们需要使用 declare var 来定义它的类型
declare var jQuery: (selector: string) => any;
jQuery('#foo');
2
3
上例中,declare var 并没有真的定义一个变量,只是定义了全局变量 jQuery 的类型,仅仅会用于编译时的检查,在编译结果中会被删除。它编译结果是:
jQuery('#foo');
# 什么是声明文件
通常我们会把声明语句放到一个单独的文件(jQuery.d.ts)中,这就是声明文件
// src/jQuery.d.ts
declare var jQuery: (selector: string) => any;
2
3
// src/index.ts
jQuery('#foo');
2
3
声明文件必需以 .d.ts 为后缀。
一般来说,ts 会解析项目中所有的 *.ts 文件,当然也包含以 .d.ts 结尾的文件。所以当我们将 jQuery.d.ts 放到项目中时,其他所有 *.ts 文件就都可以获得 jQuery 的类型定义了。
# 第三方声明文件
jQuery 的声明文件不需要我们定义了
我们可以直接下载下来使用,但是更推荐的是使用 @types 统一管理第三方库的声明文件。
@types 的使用方式很简单,直接用 npm 安装对应的声明模块即可,以 jQuery 举例:
npm install @types/jquery --save-dev
# 书写声明文件
库的使用场景主要有以下几种:
- 全局变量:通过
<script>标签引入第三方库,注入全局变量 - npm 包:通过
import foo from 'foo'导入,符合 ES6 模块规范 - UMD 库:既可以通过
<script>标签引入,又可以通过import导入 - 直接扩展全局变量:通过
<script>标签引入后,改变一个全局变量的结构 - 在 npm 包或 UMD 库中扩展全局变量:引用 npm 包或 UMD 库后,改变一个全局变量的结构
- 模块插件:通过
<script>或import导入后,改变另一个模块的结构
declare var
declare let jQuery: (selector: string) => any;
// 一般用下面的
declare const jQuery: (selector: string) => any;
2
3
declare function
declare function jQuery(selector: string): any;
declare class
当全局变量是一个类的时候,我们用 declare class 来定义它的类型
declare class Animal {
name: string;
constructor(name: string);
sayHi(): string;
}
2
3
4
5
同样的,declare class 语句也只能用来定义类型,不能用来定义具体的实现,比如定义 sayHi 方法的具体实现则会报错:
// src/Animal.d.ts
declare class Animal {
name: string;
constructor(name: string);
sayHi() {
return `My name is ${this.name}`;
};
// ERROR: An implementation cannot be declared in ambient contexts.
}
2
3
4
5
6
7
8
9
10
declare enum
使用 declare enum 定义的枚举类型也称作外部枚举(Ambient Enums)
// src/Directions.d.ts
declare enum Directions {
Up,
Down,
Left,
Right
}
2
3
4
5
6
7
8
// src/index.ts
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];
2
3
interface和type
除了全局变量之外,可能有一些类型我们也希望能暴露出来。在类型声明文件中,我们可以直接使用 interface 或 type 来声明一个全局的接口或类型
// src/jQuery.d.ts
interface AjaxSettings {
method?: 'GET' | 'POST'
data?: any;
}
declare namespace jQuery {
function ajax(url: string, settings?: AjaxSettings): void;
}
2
3
4
5
6
7
8
9
防止命名冲突
暴露在最外层的 interface 或 type 会作为全局类型作用于整个项目中,我们应该尽可能的减少全局变量或全局类型的数量。
npm包
一般我们通过 import foo from 'foo' 导入一个 npm 包,这是符合 ES6 模块规范的。
在我们尝试给一个 npm 包创建声明文件之前,需要先看看它的声明文件是否已经存在。一般来说,npm 包的声明文件可能存在于两个地方:
- 与该 npm 包绑定在一起。判断依据是
package.json中有types字段,或者有一个index.d.ts声明文件。这种模式不需要额外安装其他包,是最为推荐的,所以以后我们自己创建 npm 包的时候,最好也将声明文件与 npm 包绑定在一起。 - 发布到
@types里。我们只需要尝试安装一下对应的@types包就知道是否存在该声明文件,安装命令是npm install @types/foo --save-dev。这种模式一般是由于 npm 包的维护者没有提供声明文件,所以只能由其他人将声明文件发布到@types里了。
# 内置对象
JS有很多内置对象,它们可以直接在TS中当定义好的类型。
内置对象是指根据标准在全局作用域(Global)上存在的对象。这里的标准是指 ECMAScript 和其他环境(比如 DOM)的标准。
# ECMAScript 的内置对象
Boolean、Error、Date、RegExp 等。
let b: Boolean = new Boolean(1);
let e: Error = new Error('Error occurred');
let d: Date = new Date();
let r: RegExp = /[a-z]/;
2
3
4
更多的内置对象,可以查看 MDN 的文档。
而他们的定义文件,则在 TypeScript 核心库的定义文件中。
# DOM 和 BOM 的内置对象
DOM 和 BOM 提供的内置对象有:
Document、HTMLElement、Event、NodeList 等。
TypeScript 中会经常用到这些类型:
let body: HTMLElement = document.body;
let allDiv: NodeList = document.querySelectorAll('div');
document.addEventListener('click', function(e: MouseEvent) {
// Do something
});
2
3
4
5
它们的定义文件同样在 TypeScript 核心库的定义文件中。
# 用 TypeScript 写 Node.js
ode.js 不是内置对象的一部分,如果想用 TypeScript 写 Node.js,则需要引入第三方声明文件:
npm install @types/node --save-dev
# 进阶
# 类型别名
例子:
type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver): Name {
if (typeof n === 'string') {
return n;
} else {
return n();
}
}
2
3
4
5
6
7
8
9
10
上例中,我们使用 type 创建类型别名。
类型别名常用于联合类型。
# 字符串字面量类型
字符串字面量类型用来约束取值只能是某几个字符串中的一个。
type EventNames = 'click' | 'scroll' | 'mousemove';
function handleEvent(ele: Element, event: EventNames) {
// do something
}
handleEvent(document.getElementById('hello'), 'scroll'); // 没问题
handleEvent(document.getElementById('world'), 'dblclick'); // 报错,event 不能为 'dblclick'
// index.ts(7,47): error TS2345: Argument of type '"dblclick"' is not assignable to parameter of type 'EventNames'.
2
3
4
5
6
7
8
9
# 元组
数组合并了相同类型的对象,而元组(Tuple)合并了不同类型的对象。
元组起源于函数编程语言(如 F#),这些语言中会频繁使用元组。
例如:
let tom: [string, number] = ['Tom', 25];
元组当添加越界的元素时,它的类型会被限制为元组中每个类型的联合类型
let tom: [string, number];
tom = ['Tom', 25];
tom.push('male');
tom.push(true);
// Argument of type 'true' is not assignable to parameter of type 'string | number'.
2
3
4
5
6
7
# 枚举
枚举(Enum)类型用于取值被限定在一定范围内的场景
enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"] === 0); // true
console.log(Days["Mon"] === 1); // true
console.log(Days["Tue"] === 2); // true
console.log(Days["Sat"] === 6); // true
console.log(Days[0] === "Sun"); // true
console.log(Days[1] === "Mon"); // true
console.log(Days[2] === "Tue"); // true
console.log(Days[6] === "Sat"); // true
2
3
4
5
6
7
8
9
10
# 手动赋值
我们也可以给枚举项手动赋值
enum Days {Sun = 7, Mon = 1, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"] === 7); // true
console.log(Days["Mon"] === 1); // true
console.log(Days["Tue"] === 2); // true
console.log(Days["Sat"] === 6); // true
2
3
4
5
6
如果未手动赋值的枚举项与手动赋值的重复了,TypeScript 是不会察觉到这一点的
enum Days {Sun = 3, Mon = 1, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"] === 3); // true
console.log(Days["Wed"] === 3); // true
console.log(Days[3] === "Sun"); // false
console.log(Days[3] === "Wed"); // true
2
3
4
5
6
动赋值的枚举项可以不是数字,此时需要使用类型断言来让 tsc 无视类型检查
enum Days {Sun = 7, Mon, Tue, Wed, Thu, Fri, Sat = <any>"S"};
手动赋值的枚举项也可以为小数或负数,此时后续未手动赋值的项的递增步长仍为 1
enum Days {Sun = 7, Mon = 1.5, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"] === 7); // true
console.log(Days["Mon"] === 1.5); // true
console.log(Days["Tue"] === 2.5); // true
console.log(Days["Sat"] === 6.5); // true
2
3
4
5
6
# 常数项和计算所得项
枚举项有两种类型:常数项(constant member)和计算所得项(computed member)
计算所得项例如
enum Color {Red, Green, Blue = "blue".length};
如果紧接在计算所得项后面的是未手动赋值的项,那么它就会因为无法获得初始值而报错:
enum Color {Red = "red".length, Green, Blue};
// index.ts(1,33): error TS1061: Enum member must have initializer.
// index.ts(1,40): error TS1061: Enum member must have initializer.
2
3
4
# 常数枚举
常数枚举是使用 const enum 定义的枚举类型:
const enum Directions {
Up,
Down,
Left,
Right
}
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];
2
3
4
5
6
7
8
常数枚举与普通枚举的区别是,它会在编译阶段被删除,并且不能包含计算成员。
# 外部枚举
外部枚举(Ambient Enums)是使用 declare enum 定义的枚举类型:
declare enum Directions {
Up,
Down,
Left,
Right
}
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];
2
3
4
5
6
7
8
declare 定义的类型只会用于编译时的检查,编译结果中会被删除。
# 类Class
传统方法中,JavaScript 通过构造函数实现类的概念,通过原型链实现继承。而在 ES6 中,我们终于迎来了 class。
# 类的概念
- 类(Class):定义了一件事物的抽象特点,包含它的属性和方法
- 对象(Object):类的实例,通过
new生成 - 面向对象(OOP)的三大特性:封装、继承、多态
- 封装(Encapsulation):将对数据的操作细节隐藏起来,只暴露对外的接口。外界调用端不需要(也不可能)知道细节,就能通过对外提供的接口来访问该对象,同时也保证了外界无法任意更改对象内部的数据
- 继承(Inheritance):子类继承父类,子类除了拥有父类的所有特性外,还有一些更具体的特性
- 多态(Polymorphism):由继承而产生了相关的不同的类,对同一个方法可以有不同的响应。比如
Cat和Dog都继承自Animal,但是分别实现了自己的eat方法。此时针对某一个实例,我们无需了解它是Cat还是Dog,就可以直接调用eat方法,程序会自动判断出来应该如何执行eat - 存取器(getter & setter):用以改变属性的读取和赋值行为
- 修饰符(Modifiers):修饰符是一些关键字,用于限定成员或类型的性质。比如
public表示公有属性或方法 - 抽象类(Abstract Class):抽象类是供其他类继承的基类,抽象类不允许被实例化。抽象类中的抽象方法必须在子类中被实现
- 接口(Interfaces):不同类之间公有的属性或方法,可以抽象成一个接口。接口可以被类实现(implements)。一个类只能继承自另一个类,但是可以实现多个接口
# ES6中类的用法
# 属性和方法
使用 class 定义类,使用 constructor 定义构造函数。
通过 new 生成新实例的时候,会自动调用构造函数。
class Animal {
name;
constructor(name) {
this.name = name;
}
sayHi() {
return `My name is ${this.name}`;
}
}
let a = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack
2
3
4
5
6
7
8
9
10
11
12
# 类的继承
使用 extends 关键字实现继承,子类中使用 super 关键字来调用父类的构造函数和方法。
class Cat extends Animal {
constructor(name) {
super(name); // 调用父类的 constructor(name)
console.log(this.name);
}
sayHi() {
return 'Meow, ' + super.sayHi(); // 调用父类的 sayHi()
}
}
let c = new Cat('Tom'); // Tom
console.log(c.sayHi()); // Meow, My name is Tom
2
3
4
5
6
7
8
9
10
11
12
# 存取器
使用 getter 和 setter 可以改变属性的赋值和读取行为
class Animal {
constructor(name) {
this.name = name;
}
get name() {
return 'Jack';
}
set name(value) {
console.log('setter: ' + value);
}
}
let a = new Animal('Kitty'); // setter: Kitty
a.name = 'Tom'; // setter: Tom
console.log(a.name); // Jack
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 静态方法
使用 static 修饰符修饰的方法称为静态方法,它们不需要实例化,而是直接通过类来调用
class Animal {
static isAnimal(a) {
return a instanceof Animal;
}
}
let a = new Animal('Jack');
Animal.isAnimal(a); // true
a.isAnimal(a); // TypeError: a.isAnimal is not a function
2
3
4
5
6
7
8
9
# ES7中类的用法
# 实例属性
ES6 中实例的属性只能通过构造函数中的 this.xxx 来定义,ES7 提案中可以直接在类里面定义:
class Animal {
name = 'Jack';
constructor() {
// ...
}
}
let a = new Animal();
console.log(a.name); // Jack
2
3
4
5
6
7
8
9
10
# 静态属性
ES7 提案中,可以使用 static 定义一个静态属性
class Animal {
static num = 42;
constructor() {
// ...
}
}
console.log(Animal.num); // 42
2
3
4
5
6
7
8
9
# TypeScript 中类的用法
# public private 和 protected
TypeScript 可以使用三种访问修饰符(Access Modifiers),分别是 public、private 和 protected。
public修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是public的private修饰的属性或方法是私有的,不能在声明它的类的外部访问protected修饰的属性或方法是受保护的,它和private类似,区别是它在子类中也是允许被访问的
class Animal {
public name;
public constructor(name) {
this.name = name;
}
}
let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
console.log(a.name); // Tom
2
3
4
5
6
7
8
9
10
11
上面的例子中,name 被设置为了 public,所以直接访问实例的 name 属性是允许的。
很多时候,我们希望有的属性是无法直接存取的,这时候就可以用 private 了
class Animal {
private name;
public constructor(name) {
this.name = name;
}
}
let a = new Animal('Jack');
console.log(a.name);
a.name = 'Tom';
// index.ts(9,13): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
// index.ts(10,1): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
2
3
4
5
6
7
8
9
10
11
12
13
用 protected 修饰,则允许在子类中访问
class Animal {
protected name;
public constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
super(name);
console.log(this.name);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
当构造函数修饰为 private 时,该类不允许被继承或者实例化:
class Animal {
public name;
private constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
super(name);
}
}
let a = new Animal('Jack');
// index.ts(7,19): TS2675: Cannot extend a class 'Animal'. Class constructor is marked as private.
// index.ts(13,9): TS2673: Constructor of class 'Animal' is private and only accessible within the class declaration.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
当构造函数修饰为 protected 时,该类只允许被继承:
class Animal {
public name;
protected constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
super(name);
}
}
let a = new Animal('Jack');
// index.ts(13,9): TS2674: Constructor of class 'Animal' is protected and only accessible within the class declaration.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# readonly
只读属性关键字,只允许出现在属性声明或索引签名或构造函数中。
class Animal {
readonly name;
public constructor(name) {
this.name = name;
}
}
let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
// index.ts(10,3): TS2540: Cannot assign to 'name' because it is a read-only property.
2
3
4
5
6
7
8
9
10
11
12
注意如果 readonly 和其他访问修饰符同时存在的话,需要写在其后面。
class Animal {
// public readonly name;
public constructor(public readonly name) {
// this.name = name;
}
}
2
3
4
5
6
# 抽象类
abstract 用于定义抽象类和其中的抽象方法。
1.抽象类是不允许被实例化的
abstract class Animal {
public name;
public constructor(name) {
this.name = name;
}
public abstract sayHi();
}
let a = new Animal('Jack');
// index.ts(9,11): error TS2511: Cannot create an instance of the abstract class 'Animal'.
2
3
4
5
6
7
8
9
10
11
2.抽象类中的抽象方法必须被子类实现
abstract class Animal {
public name;
public constructor(name) {
this.name = name;
}
public abstract sayHi();
}
class Cat extends Animal {
public eat() {
console.log(`${this.name} is eating.`);
}
}
let cat = new Cat('Tom');
// index.ts(9,7): error TS2515: Non-abstract class 'Cat' does not implement inherited abstract member 'sayHi' from class 'Animal'.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
下面是一个正确使用抽象类的例子:
abstract class Animal {
public name;
public constructor(name) {
this.name = name;
}
public abstract sayHi();
}
class Cat extends Animal {
public sayHi() {
console.log(`Meow, My name is ${this.name}`);
}
}
let cat = new Cat('Tom');
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 类的类型
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
sayHi(): string {
return `My name is ${this.name}`;
}
}
let a: Animal = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack
2
3
4
5
6
7
8
9
10
11
12
# 类与接口
接口不仅可以用于对 对象的形状 进行描述,还可用于对类的一部分行为进行抽象。
# 类实现接口 implements
有时候不同类之间可以有一些共有的特性,这时候就可以把特性提取成接口(interfaces),用 implements 关键字来实现。这个特性大大提高了面向对象的灵活性。
interface Alarm {
alert(): void;
}
class Door {
}
class SecurityDoor extends Door implements Alarm {
alert() {
console.log('SecurityDoor alert');
}
}
class Car implements Alarm {
alert() {
console.log('Car alert');
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 接口继承接口
interface Alarm {
alert(): void;
}
interface LightableAlarm extends Alarm {
lightOn(): void;
lightOff(): void;
}
2
3
4
5
6
7
8
# 接口继承类
常见的面向对象语言中,接口是不能继承类的,但是在 TypeScript 中却是可以的:
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
interface Point3d extends Point {
z: number;
}
let point3d: Point3d = {x: 1, y: 2, z: 3};
2
3
4
5
6
7
8
9
10
11
12
13
14
也可以将 Point 当做一个类型来用
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
function printPoint(p: Point) {
console.log(p.x, p.y);
}
printPoint(new Point(1, 2));
2
3
4
5
6
7
8
9
10
11
12
13
14
这个例子实际上可以等价于
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
interface PointInstanceType {
x: number;
y: number;
}
function printPoint(p: PointInstanceType) {
console.log(p.x, p.y);
}
printPoint(new Point(1, 2));
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
上例中我们新声明的 PointInstanceType 类型,与声明 class Point 时创建的 Point 类型是等价的。
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
interface PointInstanceType {
x: number;
y: number;
}
// 等价于 interface Point3d extends PointInstanceType
interface Point3d extends Point {
z: number;
}
let point3d: Point3d = {x: 1, y: 2, z: 3};
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
当我们声明 interface Point3d extends Point 时,Point3d 继承的实际上是类 Point 的实例的类型。
换句话说,可以理解为定义了一个接口 Point3d 继承另一个接口 PointInstanceType。
值得注意的是,PointInstanceType 相比于 Point,缺少了 constructor 方法,这是因为声明 Point 类时创建的 Point 类型是不包含构造函数的。另外,除了构造函数是不包含的,静态属性或静态方法也是不包含的(实例的类型当然不应该包括构造函数、静态属性或静态方法)。
# 泛型
泛型(Generics)是指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性。
function createArray(length: number, value: any): Array<any> {
let result = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
createArray(3, 'x'); // ['x', 'x', 'x']
2
3
4
5
6
7
8
9
上面这段代码没有准确的定义返回值的类型。Array<any> 允许数组的每一项都为任意类型。但是我们预期的是,数组中每一项都应该是输入的 value 的类型。
这时候,泛型就派上用场了:
function createArray<T>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
createArray<string>(3, 'x'); // ['x', 'x', 'x']
2
3
4
5
6
7
8
9
接着在调用的时候,可以指定它具体的类型为 string。当然,也可以不手动指定,而让类型推论自动推算出来:
function createArray<T>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
createArray(3, 'x'); // ['x', 'x', 'x']
2
3
4
5
6
7
8
9
# 多个类型参数
定义泛型的时候,可以一次定义多个类型参数
function swap<T, U>(tuple: [T, U]): [U, T] {
return [tuple[1], tuple[0]];
}
swap([7, 'seven']); // ['seven', 7]
2
3
4
5
# 泛型约束
在函数内部使用泛型变量的时候,由于事先不知道它是哪种类型,所以不能随意的操作它的属性或方法
function loggingIdentity<T>(arg: T): T {
console.log(arg.length);
return arg;
}
// index.ts(2,19): error TS2339: Property 'length' does not exist on type 'T'.
2
3
4
5
6
上例中,泛型 T 不一定包含属性 length,所以编译的时候报错了。
这时,我们可以对泛型进行约束,只允许这个函数传入那些包含 length 属性的变量。这就是泛型约束
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
2
3
4
5
6
7
8
上例中,我们使用了 extends 约束了泛型 T 必须符合接口 Lengthwise 的形状,也就是必须包含 length 属性。
此时如果调用 loggingIdentity 的时候,传入的 arg 不包含 length,那么在编译阶段就会报错了:
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
loggingIdentity(7);
// index.ts(10,17): error TS2345: Argument of type '7' is not assignable to parameter of type 'Lengthwise'.
2
3
4
5
6
7
8
9
10
11
12
多个类型参数之间也可以互相约束
function copyFields<T extends U, U>(target: T, source: U): T {
for (let id in source) {
target[id] = (<T>source)[id];
}
return target;
}
let x = { a: 1, b: 2, c: 3, d: 4 };
copyFields(x, { b: 10, d: 20 });
2
3
4
5
6
7
8
9
10
上例中,我们使用了两个类型参数,其中要求 T 继承 U,这样就保证了 U 上不会出现 T 中不存在的字段。
# 泛型接口
可以使用接口的方式来定义一个函数需要符合的形状
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
return source.search(subString) !== -1;
}
2
3
4
5
6
7
使用含有泛型的接口来定义函数的形状
interface CreateArrayFunc {
<T>(length: number, value: T): Array<T>;
}
let createArray: CreateArrayFunc;
createArray = function<T>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
createArray(3, 'x'); // ['x', 'x', 'x']
2
3
4
5
6
7
8
9
10
11
12
13
14
我们可以把泛型参数提前到接口名上:
interface CreateArrayFunc<T> {
(length: number, value: T): Array<T>;
}
let createArray: CreateArrayFunc<any>;
createArray = function<T>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
createArray(3, 'x'); // ['x', 'x', 'x']
2
3
4
5
6
7
8
9
10
11
12
13
# 泛型类
与泛型接口类似,泛型也可以用于类的类型定义中
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };
2
3
4
5
6
7
8
在 TypeScript 2.3 以后,我们可以为泛型中的类型参数指定默认类型。当使用泛型时没有在代码中直接指定类型参数,从实际值参数中也无法推测出时,这个默认类型就会起作用。
function createArray<T = string>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
2
3
4
5
6
7
← Geometry