TypeScript 中 type 和 interface 的区别与选择
在 TypeScript 里定义对象类型时,很多人会纠结用 type 还是 interface。比如定义一个用户对象,两种写法都可以:
// 使用 interface
interface User {
name: string;
avatar: string;
level: number;
}
// 使用 type
type User = {
name: string;
avatar: string;
level: number;
};这两种写法效果差不多,但实际用起来有不少区别。下面我们来详细看看。
1. 继承方式不同
interface 用 extends 实现继承:
interface UserBasic extends User {
email: string;
}type 用 & 实现类型合并:
type UserBasic = {
email: string;
} & User;看起来结果一样,但 interface 的继承更接近传统面向对象的概念。另外,interface 不能直接继承基本类型(比如 string),但 type 可以:
type S = string & number & {}; // 没问题2. 扩展方式不同
interface 支持声明合并。如果你多次定义同名的 interface,TypeScript 会把它们合并在一起:
interface User {
email: string;
}
interface User {
phone: number;
}
// 最终 User 包含 email 和 phone这个特性在扩展第三方库类型时特别有用。比如给数组加一个自定义方法:
interface Array<T> {
last(): T | undefined;
}
Array.prototype.last = function() {
return this[this.length - 1];
};type 不允许重复定义同名类型,会直接报错。
3. 类实现方面
两种方式都可以被类实现:
// 用 interface
interface IUser {
name?: string;
age: number;
isAdult(): boolean;
}
class User implements IUser {
age = 16;
isAdult() {
return this.age >= 18;
}
}
// 用 type
type IUser = {
name?: string;
age: number;
isAdult(): boolean;
}
class User implements IUser {
age = 16;
isAdult() {
return this.age >= 18;
}
}在这方面,两者没有区别。
4. 功能范围不同
type 其实是为类型起别名,可以定义各种类型:
基本类型别名:type ID = string;
联合类型:type Status = 'pending' | 'success' | 'error';
元组类型:type Point = [number, number];
函数类型:type ClickHandler = (event: MouseEvent) => void;
interface 主要用来定义对象类型,是更“标准”的对象类型定义方式。
5. 开发体验差异
在编辑器中,把鼠标放在 type 定义的类型上时,会直接显示详细结构。而 interface 通常只显示名称,需要点击查看详情。这个小区别有时会影响开发效率。
如何选择?
根据上面的比较,可以得出以下建议:
如果需要声明合并(比如扩展第三方类型),只能用 interface
如果需要定义联合类型、元组等复杂类型,只能用 type
定义对象类型时,两者都可以,但有一些偏好:
面向对象编程,尤其是类实现时,优先考虑 interface
简单的对象类型,根据团队习惯选择
需要更清晰的类型提示时,可以考虑 type
实际项目中的建议
对于新手,可以这样开始:
定义对象类型时,先默认用 interface
遇到 interface 做不到的情况时(比如需要联合类型),换用 type
团队统一规范,保持代码一致性
对于有经验的团队,可以制定更详细的规则,比如:
公共 api 用 interface,方便扩展
内部使用的复杂类型用 type
简单的交叉类型用 type
记住,TypeScript 官方也表示,未来两种方式的差异可能会进一步缩小。所以不需要过度纠结,保持一致性更重要。
总结
type 和 interface 在 TypeScript 中各有优势。interface 更适合传统的面向对象编程,支持声明合并;type 更灵活,能定义各种复杂类型。在实际项目中,根据具体需求选择,保持团队统一规范即可。随着 TypeScript 版本更新,两者的功能会越来越接近,掌握核心区别就能做出正确选择。
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!