外观
接口别名
类型别名就是给类型起个名字。
基本语法
使用 type 关键字,后跟类型名称,名称为合法的标识符,首字母大写,类型可以是任意类型,包括原始类型、对象类型、联合类型、交叉类型等。
ts
type Numeric = number | bigint
type StringOrNumber = string | Numeric类型别名递归
类型别名中可引用自身,这非常适用于定义树形结构、嵌套对象等数据结构。
ts
// 树节点
type TreeNode = {
value: number
children?: TreeNod[] // 递归引用自身
}
// JSON数据,| 是分隔符不是运算符,| A | B 的写法等价 A | B,系统会自动处理冗余竖线
type Json =
| string
| number
| boolean
| null
| Json[]
| { [key: string]: Json }注意避免无限递归,确保要有终止条件。虽然无限递归的类型定义本身不报错,但使用时会报无法满足条件的错误。
ts
type T = {
next: T
}
// ❌ 永远无法满足,因为next的值不能为空对象
const obj: T = {
next: {}
}递归添加终止条件:
ts
// 方式一,使用可选属性
type T = {
next?: T
}
// 方式二,联合类型提供出口
// 递归但有string这个基础类型终止
type T = string | { [key: string]: T }类型别名与接口
- 类型别名能表示非对象类型,而接口只能表示对象类型。
- 接口可继承其他接口,而类型别名不支持继承。
- 同名接口会合并声明,而同名的类型别名会报错。