TypeScript 类型别名
上一章讲了 interface,这一章讲它的"兄弟"——type 类型别名。type 能做的事比 interface 更多:除了描述对象形状,还能给基础类型起名字、定义字面量类型、联合类型、交叉类型。两者有很多重叠,初学者常纠结该用哪个——这一章也会给出明确的选择建议。
1. type 的基本用法
type 用等号给类型起一个名字。描述对象时,写法和 interface 几乎一样:
// type 给类型起一个名字(别名),用法和 interface 很像
type User = {
id: number;
name: string;
age: number;
};
const u: User = { id: 1, name: "小明", age: 20 };
// 也能描述函数类型(这场景 type 比 interface 更常用)
type Greet = (name: string) => string;
const greet: Greet = (n) => "你好, " + n;2. 字面量类型 —— type 的强项
这是 type 最有用的特性之一。你可以把一个具体的值当成类型——这意味着变量只能取这个值。单个字面量没意义,但组合成联合类型后就非常强大:
// 字面量类型:把"具体的值"当成类型
let x: "hello" = "hello";
// x = "hi"; // ❌ 报错:只能赋 "hello"
// 单个字面量没意义,组合成联合类型就很有用
type Status = "idle" | "loading" | "success" | "error";
let page: Status = "loading"; // 只能取这四个值之一
// 数字字面量也行
type Dice = 1 | 2 | 3 | 4 | 5 | 6;
let roll: Dice = 4;
// 字面量类型非常适合描述状态机、配置项这类"取值有限"的场景
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";字面量类型是描述状态机、配置项、API 方法这类"取值有限"场景的最佳工具。这是 interface 做不到的。
3. 联合与交叉类型
联合类型(|)表示"或",交叉类型(&)表示"且"。这两者是组合复杂类型的核心工具,下一篇会专门讲。这里先认识它们的写法:
// 联合类型(详细一篇会讲,这里先认识)
type ID = number | string;
let id: ID = 123;
id = "abc-001";
// 交叉类型:把多个类型合并
type WithTime = { createdAt: string };
type WithAuthor = { author: string };
type Article = WithTime & WithAuthor;
const post: Article = {
createdAt: "2025-08-05",
author: "小明",
};4. 给基础类型起别名
interface 只能描述对象形状,而 type 能给任何类型起名字——包括基础类型、元组、数组。这在"语义化命名"时很有用:
// type 能给基础类型起别名(interface 不行)
type Score = number;
type Name = string;
// 也能给数组、元组起别名
type Point = [number, number];
type NumberList = number[];
// 实际项目里常用于"语义化命名"
type UserId = string; // 强调这是用户 id,不是普通字符串
type Email = string;5. type vs interface:怎么选?
这是 TS 社区经典问题。结论其实很简单——两者大部分时候可以互换,但有几点区别:
// interface 和 type 的核心区别:
// 1. 写法:interface 用关键字,type 用等号
interface A { x: number }
type B = { x: number };
// 2. 合并:同名 interface 会自动合并,type 会报错
interface Window { a: string }
interface Window { b: string } // 合并成功,Window 同时有 a 和 b
type T = { a: string }
// type T = { b: string } // ❌ 报错:不能重复声明 "T"
// 3. 扩展语法不同
interface C extends A { y: number }
type D = B & { y: number }; // type 用交叉类型扩展
// 4. type 能描述基础类型/联合/元组/interface 不能
type E = string | number; // ✅
// interface F = string | number; // ❌ 语法错误实战选择建议:
- 描述对象/类的形状(如 User、TodoItem、组件 props)→ 优先
interface(可扩展、可合并,更"面向对象")。 - 联合、交叉、字面量、函数、元组、基础类型别名 → 用
type(interface 做不到)。 - 团队统一即可,不要混用太多。React/Vue 社区倾向 interface 优先。
6. 实战示例:API 响应类型
把 type 和 interface 组合起来,描述一个典型的 API 响应:
小结
type 别名比 interface 更灵活:能描述基础类型、字面量、联合、交叉、元组。两者描述对象时几乎等价。对象优先 interface,其他场景用 type。下一篇讲 TS 的另一个重点——函数的类型标注。
← 上一篇 TypeScript 接口
下一篇 TypeScript 函数 →