Leecason

vuePress-theme-reco Leecason    2018 - 2020
Leecason Leecason

Choose mode

  • dark
  • auto
  • light
主页
分类
  • CSS
  • FrontEnd
  • GraphQL
  • JavaScript
  • TypeScript
  • Vue
  • Webpack
  • 其它
  • 数据结构与算法
  • 浏览器相关
标签
时间线
GitHub
author-avatar

Leecason

80

Article

61

Tag

主页
分类
  • CSS
  • FrontEnd
  • GraphQL
  • JavaScript
  • TypeScript
  • Vue
  • Webpack
  • 其它
  • 数据结构与算法
  • 浏览器相关
标签
时间线
GitHub

TypeScript 进阶使用

vuePress-theme-reco Leecason    2018 - 2020

TypeScript 进阶使用

Leecason 2020-02-19

本文介绍 TypeScript 中的一些高级的类型与技术。

# 类型别名

用来给一个类型起个新名字。

type Name = string;

type NameResolver = () => string;

type NameOrResolver = Name | NameResolver;

function getName(n: NameOrResolver): Name {
  if (typeof n === 'string') {
    return n;
  } else {
    return n();
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 字符串字面量类型

用来约束取值只能是某几个字符串中的一个。

type EventNames = 'click' | 'scroll' | 'mousemove';

function handleEvent(ele: Element, event: EventNames) {
  // do something
}

handleEvent(document.getElementById('hello'), 'scroll');  // 没问题
handleEvent(document.getElementById('world'), 'dbclick'); // 报错,event 不能为 'dbclick'
1
2
3
4
5
6
7
8

注意,「类型别名」与「字符串字面量类型」都是使用 type 进行定义。

# 元祖

元组(Tuple)合并了不同类型的对象。

元组起源于函数编程语言(如 F#),这些语言中会频繁使用元组。

// 定义一对值分别为 string 和 number 的元组:
let tom: [string, number] = ['Tom', 25];

let tom: [string, number];
tom = ['Tom']; // 报错,直接对元组类型的变量进行初始化或者赋值的时候,需要提供所有元组类型中指定的项。

// 越界的元素
let tom: [string, number];
tom = ['Tom', 25];
tom.push('male'); // 没问题
tom.push(true); // 报错,当添加越界的元素时,它的类型会被限制为元组中每个类型的联合类型
1
2
3
4
5
6
7
8
9
10
11

# 枚举

枚举(Enum)类型用于取值被限定在一定范围内的场景,比如一周只能有七天,颜色限定为红绿蓝等。

enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};

// 枚举成员会被赋值为从 0 开始递增的数字,同时也会对枚举值到枚举名进行反向映射
Days["Sun"] === 0 // true
Days[0] === "Sun" // true
1
2
3
4
5

# 手动赋值

enum Days {Sun = 7, Mon = 1, Tue, Wed, Thu, Fri, Sat};

Days["Sun"] === 7 // true
Days["Mon"] === 1 // true

// 未手动赋值的枚举项会接着上一个枚举项递增
Days["Tue"] === 2 // true

//手动赋值的枚举项可以不是数字,此时需要使用类型断言来让 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};

Days["Sun"] === 7 // true
Days["Mon"] === 1.5 // true
Days["Tue"] === 2.5 // true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 常数项和计算所得项

枚举项有两种类型:常数项(constant member)和计算所得项(computed member)。

前面所举的例子都是常数项,下面为计算所得项。

enum Color {Red, Green, Blue = "blue".length};

// 如果紧接在计算所得项后面的是未手动赋值的项,那么它就会因为无法获得初始值而报错
enum Color {Red = "red".length, Green, Blue}; // 报错
1
2
3
4

# 常数枚举

常数枚举是使用 const enum 定义的枚举类型。

const enum Directions {
  Up,
  Down,
  Left,
  Right
}

let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];
// 常数枚举与普通枚举的区别是,它会在编译阶段被删除,并且不能包含计算成员。
// 编译结果:
var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */];

const enum Color {Red, Green, Blue = "blue".length}; // 报错,不能包含计算成员
1
2
3
4
5
6
7
8
9
10
11
12
13

# 外部枚举

外部枚举(Ambient Enums)是使用 declare enum 定义的枚举类型。

declare enum Directions {
  Up,
  Down,
  Left,
  Right
}

let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];

// declare 定义的类型只会用于编译时的检查,编译结果中会被删除。
// 编译结果:
var directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];
1
2
3
4
5
6
7
8
9
10
11
12

同时使用 declare 和 const:

declare const enum Directions {
  Up,
  Down,
  Left,
  Right
}

let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];

// 编译结果:
var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */];
1
2
3
4
5
6
7
8
9
10
11

# 类

# 类的概念

  • 类(Class):定义了一件事物的抽象特点,包含它的属性和方法
  • 对象(Object):类的实例,通过 new 生成
  • 面向对象(OOP)的三大特性:封装、继承、多态
  • 封装(Encapsulation):将对数据的操作细节隐藏起来,只暴露对外的接口。外界调用端不需要- (也不可能)知道细节,就能通过对外提供的接口来访问该对象,同时也保证了外界无法任意更改对象内部的数据
  • 继承(Inheritance):子类继承父类,子类除了拥有父类的所有特性外,还有一些更具体的特性
  • 多态(Polymorphism):由继承而产生了相关的不同的类,对同一个方法可以有不同的响应。比如 Cat 和 Dog 都继承自 Animal,但是分别实现了自己的 eat 方法。此时针对某一个实例,我们无需了解它是 Cat 还是 Dog,就可以直接调用 eat 方法,程序会自动判断出来应该如何执行 eat
  • 存取器(getter & setter):用以改变属性的读取和赋值行为
  • 修饰符(Modifiers):修饰符是一些关键字,用于限定成员或类型的性质。比如 public 表示公有属性或方法
  • 抽象类(Abstract Class):抽象类是供其他类继承的基类,抽象类不允许被实例化。抽象类中的抽象方法必须在子类中被实现
  • 接口(Interfaces):不同类之间公有的属性或方法,可以抽象成一个接口。接口可以被类实现(implements)。一个类只能继承自另一个类,但是可以实现多个接口

# public private 和 protected

TypeScript 可以使用三种访问修饰符(Access Modifiers)

  • public 修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public 的
  • private 修饰的属性或方法是私有的,不能在声明它的类的外部访问
  • protected 修饰的属性或方法是受保护的,它和 private 类似,区别是它在子类中也是允许被访问的
class Animal {
  public name; // public 修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public 的
  public constructor(name) {
    this.name = name;
  }
}
1
2
3
4
5
6
class Animal {
  private name; // private 修饰的属性或方法是私有的,不能在声明它的类的外部访问
  public constructor(name) {
    this.name = name;
  }
}
1
2
3
4
5
6
class Animal {
  protected name; // protected 修饰的属性或方法是受保护的,它和 private 类似,区别是它在子类中也是允许被访问的
  public constructor(name) {
    this.name = name;
  }
}
1
2
3
4
5
6
class Animal {
  public name;
  private constructor (name) { // 当构造函数修饰为 private 时,该类不允许被继承或者实例化
    this.name = name;
  }
}
class Cat extends Animal {
    constructor (name) {
        super(name);
    }
}

let a = new Animal('Jack'); // 报错
1
2
3
4
5
6
7
8
9
10
11
12
13
class Animal {
  public name;
  protected constructor (name) { // 当构造函数修饰为 protected 时,该类只允许被继承
    this.name = name;
  }
}
class Cat extends Animal {
  constructor (name) {
    super(name);
  }
}

let a = new Animal('Jack'); // 报错
1
2
3
4
5
6
7
8
9
10
11
12
13

# 参数属性

// 修饰符和 `readonly` 还可以使用在构造函数参数中,等同于类中定义该属性同时给该属性赋值,使代码更简洁
class Animal {
  // public name: string;
  public constructor (public name) {
  // this.name = name;
  }
}
1
2
3
4
5
6
7

# readonly

class Animal {
  readonly name;
  public constructor(name) {
    this.name = name;
  }
}

let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom'; // 报错,只读属性
1
2
3
4
5
6
7
8
9
10

# 抽象类

abstract 用于定义抽象类和其中的抽象方法。

  • 抽象类不允许被实例化
  • 抽象类中的抽象方法必须被子类实现
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');
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 类与接口

# 类实现接口

实现(implements)是面向对象中的一个重要概念。一般来讲,一个类只能继承自另一个类,有时候不同类之间可以有一些共有的特性,这时候就可以把特性提取成接口(interfaces),用 implements 关键字来实现。

interface Alarm {
  alert();
}

class Door {
}

class SecurityDoor extends Door implements Alarm {
  alert() {
    console.log('SecurityDoor alert');
  }
}

class Car implements Alarm {
  alert() {
    console.log('Car alert');
  }
}


// 一个类实现多个接口
interface Alarm {
  alert();
}

interface Light {
  lightOn();
  lightOff();
}

class Car implements Alarm, Light {
  alert() {
    console.log('Car alert');
  }
  lightOn() {
    console.log('Car light on');
  }
  lightOff() {
    console.log('Car light off');
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

# 接口继承接口

interface Alarm {
  alert();
}

interface LightableAlarm extends Alarm {
  lightOn();
  lightOff();
}
1
2
3
4
5
6
7
8

# 接口继承类

class Point {
  x: number;
  y: number;
}

interface Point3d extends Point {
  z: number;
}

let point3d: Point3d = {x: 1, y: 2, z: 3};
1
2
3
4
5
6
7
8
9
10

# 泛型

泛型(Generics)是指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性。

// 在函数名后添加了 <T>,其中 T 用来指代任意输入的类型
function createArray<T>(length: number, value: T): Array<T> {
接着在调用的时候,可以指定它具体的类型为 string。当然,也可以不手动指定,而让类型推论自动推算出来:
  let result: T[] = [];
  for (let i = 0; i < length; i++) {
    result[i] = value;
  }
  return result;
}

// 接着在调用的时候,可以指定它具体的类型为 string
createArray<string>(3, 'x'); // ['x', 'x', 'x']
1
2
3
4
5
6
7
8
9
10
11
12

# 多个类型参数

function swap<T, U>(tuple: [T, U]): [U, T] {
  return [tuple[1], tuple[0]];
}

swap([7, 'seven']); // ['seven', 7]
1
2
3
4
5

# 泛型约束

interface Lengthwise {
  length: number;
}

// 使用 extends 约束泛型 T 必须符合接口 Lengthwise 的形状
function loggingIdentity<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

// 多个类型参数之间也可以互相约束,要求 T 继承 U
function copyFields<T extends U, U>(target: T, source: U): T {
  for (let id in source) {
    target[id] = (<T>source)[id];
  }
  return target;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 泛型接口

// 使用含有泛型的接口来定义函数的形状
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']
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 泛型类

// 用于类的类型定义
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; };
1
2
3
4
5
6
7
8
9

# 泛型参数的默认类型

// 为泛型中的类型参数指定默认类型
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;
}
1
2
3
4
5
6
7
8

# 声明合并

如果定义了两个相同名字的函数、接口或类,那么它们会合并成一个类型

# 函数的合并

// 重载定义多个函数类型
function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
  if (typeof x === 'number') {
    return Number(x.toString().split('').reverse().join(''));
  } else if (typeof x === 'string') {
    return x.split('').reverse().join('');
  }
}
1
2
3
4
5
6
7
8
9
10

# 接口的合并

interface Alarm {
  price: number;
}
interface Alarm {
  weight: number;
}

// 相当于
interface Alarm {
  price: number;
  weight: number;
}
1
2
3
4
5
6
7
8
9
10
11
12
interface Alarm {
  price: number;
}
interface Alarm {
  price: string;  // 报错,类型不一致
  weight: number;
}
1
2
3
4
5
6
7