TypeScript type 别名

type 用来给已有类型起一个"别名",让复杂的类型拥有简短、好记的名字。它并不创建新类型,只是给类型一个引用名,因此适合表示联合类型、字面量组合、对象结构与函数签名等复杂形状,是提升可读性的常用手段。

基本用法

type UserId = number; // 简单别名
type Callback = (msg: string) => void; // 函数签名别名

let uid: UserId = 1001;
const cb: Callback = (msg) => console.log(msg);
cb(`用户${uid}登录`); // 输出:用户1001登录

给对象与交叉类型起名

type Point = { x: number; y: number }; // 对象结构别名
type Colored = Point & { color: string }; // 交叉:同时具备两边属性
const dot: Colored = { x: 1, y: 2, color: "red" };
console.log(dot); // 输出:{ x: 1, y: 2, color: 'red' }

// 别名还可以复用别名
type NamedPoint = Point & { name: string };
console.log(dot.x); // 输出:1

字面量联合与可空

type 最常见的场景是把"允许的取值范围"命名成业务语义:

type Direction = "up" | "down" | "left" | "right"; // 方向只能是这四个
type Status = 0 | 1 | 2; // 数字字面量,如状态码
type MaybeNumber = number | null | undefined; // 可空数值

function move(d: Direction): string {
  return `向${d}移动`;
}
console.log(move("up")); // 输出:向上移动
// move("back"); // 报错:不在 Direction 取值范围内

泛型别名

别名同样可以带类型参数,定义成可复用的"类型工厂":

type Pair<T> = { first: T; second: T };
const p: Pair<string> = { first: "a", second: "b" };
console.log(p.first + p.second); // 输出:ab

type Result<T> = { ok: boolean; data?: T };
const r: Result<number> = { ok: true, data: 42 };
console.log(r.data); // 输出:42

type 与 interface 怎么选

维度type 别名interface 接口
同名声明的合并不允许,重复声明报错自动合并,可扩展
表达能力任意类型:联合/字面量/元组/映射主要用于对象与类契约
扩展方式& 交叉组合extends 继承
与类配合不能声明合并,可描述函数等implements 的标准选择

经验法则:需要表达"任意类型组合"(联合、字面量、函数签名)用 type;写可被扩展、被类实现的对象契约,两者皆可,团队习惯优先 interface。

小结

type 给类型起名并支持组合:联合、对象、交叉、函数签名、泛型都能表达。它不新建类型、不能同名合并,与 interface 各有所长——需要"任意类型"的表达力时选 type,需要可扩展的对象契约时选 interface。

笔记加载中…