TypeScript 类型别名

TypeScript 类型别名

本节介绍的类型别名,就是通过关键字 type 给类型起个别名,类型别名较多应用于联合类型、交叉类型这种复合类型。

1. 解释

类型别名会给类型起个新名字。类型别名有时和接口很像,但是可以作用于原始值,联合类型,元组以及其它任何你需要手写的类型。

用关键字 type 定义类型别名。

2. 举例说明

类型别名不会新建一个类型,而是创建一个新名字来引用此类型

先看下面几个例子,

原始类型:

type brand = string
type used = true | false

const str: brand = 'imooc'
const state: used = true

联合类型:

type month = string | number

const currentMonth: month = 'February'
const nextMonth: month = 

交叉类型:

interface Admin {
  id: number,
  administrator: string,
  timestamp: string
}

interface User {
  id: number,
  groups: number[],
  createLog: (id: number) => void,
  timestamp: number
}

type T = Admin & User

同接口一样,类型别名也可以是泛型:

type Tree<T, U> = {
  left: T,
  right: U
}

3. 接口 vs. 类型别名

类型别名看起来和接口非常类似,区别之处在于:

  • 接口可以实现 extends 和 implements,类型别名不行。
  • 类型别名并不会创建新类型,是对原有类型的引用,而接口会定义一个新类型。
  • 接口只能用于定义对象类型,而类型别名的声明方式除了对象之外还可以定义交叉、联合、原始类型等。

类型别名是最初 TypeScript 做类型约束的主要形式,后来引入接口之后,TypeScript 推荐我们尽可能的使用接口来规范我们的代码。

4. 小结

类型别名在定义交叉类型、联合类型时特别好用,要注意类型别名与接口的区别。