您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

TypeScript 类型别名

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

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

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

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

先看下面几个例子,

原始类型:

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
}

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

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

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


联系我
置顶