文章目录
type
和interface
均可定义类型,但核心区别在于类型扩展能力、声明合并、灵活性及适用场景。interface
更适合面向对象编程,支持继承和声明合并;type
更灵活,支持联合类型、元组等复杂类型,但不能重复声明。二者在多数场景可互换,但需根据具体需求选择。
一、核心差异对比表
特性 | interface |
type |
---|---|---|
声明合并 | ✅ 支持(同名接口自动合并) | ❌ 不允许重复声明 |
扩展方式 | extends 继承 |
& 交叉类型扩展 |
类型范围 | 仅能定义对象、函数、类结构 | 可定义任意类型(基本类型、联合类型等) |
实现(implements) | 类可通过implements 实现接口 |
类不能直接implements type定义的类型 |
性能(大型项目) | 声明合并可能增加类型系统复杂度 | 无合并问题,类型推导更稳定 |
二、核心差异详述
1. 声明合并(Declaration Merging)
-
interface
:允许同名接口自动合并,常用于扩展第三方库类型。interface User { name: string; } interface User { age: number; } // 合并为 { name: string; age: number; }
-
type
:禁止重复声明,同名type
会报错。type User = { name: string; }; type User = { age: number; }; // ❌ Error: Duplicate identifier 'User'
2. 扩展与继承方式
-
interface
:通过extends
实现继承,更符合面向对象思维。</