type 对比 interface【前端TS】
不积跬步,无以至千里;不积小流,无以成江海。
目录
- 基本定义
- 相同点
- 不同点
- 代码对比
- 1.type 定义复杂类型
- 2.interface 描述数据结构
- 3. 扩展对比
- 4.声明合并(interface 独有)
- 开发实践建议
基本定义
- type:类型别名,用来给任何合法的 TS 类型起一个名字。
- interface:专门用来描述 对象结构 或 类的契约。
相同点
- 都能描述对象、函数、类。
- 都能被 export 导出,用于模块之间共享。
- 都支持 继承/组合(方式不同)。
export type User1 = { name: string; age: number }
export interface User2 { name: string; age: number }
不同点
特性 | type | interface |
---|---|---|
定义范围 | 可以定义 任意类型(基本类型、对象、联合、交叉、元组、条件类型) | 只能定义 对象形状(对象、函数、类) |
扩展方式 | 用 交叉类型 & 扩展 | 用 extends 继承,或同名接口声明合并 |
声明合并 | ❌ 不支持,重名会报错 | ✅ 支持,同名会自动合并 |
映射/工具类型 | ✅ 可以用条件类型、映射类型等高级特性 | ❌ 不支持 |
泛型 | ✅ 支持 | ✅ 支持 |
class 实现 | ✅ 可以被 implements (但更推荐 interface) | ✅ 更常用,被设计为 class 的契约 |
可读性 | 更灵活,适合复杂类型 | 更直观,适合 API、数据结构 |
导出方式 | export type → 导出类型别名 | export interface → 导出接口 |
适用场景 | 复杂类型、联合/交叉、元组、工具类型 | 对象结构、类、可扩展 API 设计 |
代码对比
1.type 定义复杂类型
export type Status = "success" | "error" | "loading"; // 联合类型
export type Point = [number, number]; // 元组
export type UserId = string | number; // 基础类型别名
2.interface 描述数据结构
export interface User {id: number;name: string;getProfile(): string;
}
3. 扩展对比
// type:交叉类型
type A = { a: string }
type B = { b: number }
export type AB = A & B;// interface:继承
interface A { a: string }
interface B { b: number }
export interface AB extends A, B {}
4.声明合并(interface 独有)
export interface Person {name: string;
}
export interface Person {age: number;
}// 合并为:
interface Person {name: string;age: number;
}
开发实践建议
- 用 interface:
- 约束对象、类的结构
- 需要扩展或声明合并时
- 用 type:
- 需要 联合、交叉、条件类型
- 需要对基础类型或元组做别名
- 需要灵活组合复杂类型
interface:适合面向对象设计,支持继承、声明合并,更直观。
type:更灵活,能定义任意类型,适合复杂类型表达。