一句话
类型别名(type alias)就是给一个类型起个名字 ,用 type 关键字,方便复用和语义化。
ini
type UserId = string;
type Point = [number, number];
type Status = "pending" | "success" | "failed";
起完别名后,UserId 和 string 完全等价,只是名字更好懂、能复用。
一、基本语法
bash
type 别名 = 原来的类型;
ini
type Name = string;
type Age = number;
const n: Name = "张三"; // 等价于 const n: string
const a: Age = 28; // 等价于 const a: number
二、常见的 6 种用法
① 联合类型(最常用)
ini
type Status = "pending" | "success" | "failed";
let s: Status = "success"; // 只能是这三个之一
② 对象类型
ini
type User = {
id: string;
name: string;
age?: number; // 可选属性
readonly email: string; // 只读
};
const u: User = { id: "1", name: "张三", email: "a@b.com" };
③ 函数类型
typescript
type Handler = (event: string) => void;
type Add = (a: number, b: number) => number;
const add: Add = (a, b) => a + b;
④ 元组
typescript
type Pair = [string, number];
type Point = [number, number, number?];
⑤ 泛型别名
ini
type ApiResponse<T> = {
code: number;
data: T;
msg: string;
};
type UserResp = ApiResponse<{ id: string; name: string }>; // 复用 + 指定 T
⑥ 嵌套/组合(交叉类型、映射、条件类型)
typescript
type A = { a: string };
type B = { b: number };
type AB = A & B; // 交叉:既是 A 又是 B
type Partial2<T> = { [K in keyof T]?: T[K] }; // 映射类型
type IsString<T> = T extends string ? true : false; // 条件类型
三、type vs interface(面试/实战必背)
| 对比 | type |
interface |
|---|---|---|
| 定义对象 | ✅ 能 | ✅ 能 |
| 定义联合/交叉/元组/字面量 | ✅ 能 | ❌ 不能 |
| 声明合并(同名自动合并) | ❌ 不能 | ✅ 能 |
| 继承/扩展 | 用 & 交叉 |
用 extends |
| 泛型 | ✅ | ✅ |
| 常用场景 | 联合类型、工具类型、别名 | 对象/类的形状、需要扩展合并时 |
css
// interface 能"合并"(同名的自动叠加)
interface Config { a: string }
interface Config { b: number }
// 结果:Config = { a: string; b: number }
// type 同名会直接报错(不能合并)
type Config2 = { a: string };
type Config2 = { b: number }; // ❌ Duplicate identifier
选择建议:
- 需要联合类型 / 元组 / 条件类型 / 工具类型 → 用
type; - 描述对象结构 、可能要被扩展或合并 (如第三方库类型)→ 用
interface; - 拿不准就用
type,绝大多数场景够用。
四、对照你熟的 Go
| Go | TS |
|---|---|
type MyInt = int(真正的别名,完全等价) |
type Name = string |
type MyInt int(新类型,不能直接和 int 混用) |
TS 没有这种"新类型"概念,别名就是等价 |
type User struct { ... } |
type User = { ... } 或 interface User {...} |
泛型 type Pair[T any] struct{...} |
type Pair<T> = [T, T] |
关键差异 :Go 的 type A B 会造出一个新类型 (需要显式转换);TS 的 type A = B 只是别名 ,完全等价、零成本,编译后连名字都没了。
五、一句话总结
type就是"给类型起名字 + 用类型表达式描述结构"的工具 ,能干联合、元组、函数、泛型、条件类型这些interface干不了的活;代价是不能声明合并。日常写业务类型,type和interface都能用,选哪个看你要不要"合并/扩展"。