类型别名通过 type 关键字把一个类型表达式绑定到名字上。它可以为联合类型、交叉类型、函数、元组等任何类型起名,比如 type ID = number | string 就是一个可复用的联合类型。与 interface 不同,别名不能被 extends 或 implements,但它能描述任意形状,书写更直观。
实际开发中最常见的场景是给后端接口的返回结构定义别名,再搭配 Partial、Pick 等工具类型进一步派生。需要小心的是类型别名只是别名,编译后完全不存在于运行时,也不能像 interface 那样重复声明合并,但描述联合类型与交叉类型是它的主场。
type ID = number | string;
type Point = { x: number; y: number };
type Vec = Point & { z: number }; // 交叉类型
function find(id: ID): Point | null {
return id ? { x: 1, y: 2 } : null;
}
const v: Vec = { x: 1, y: 2, z: 3 };