TypeScript学习第十六篇 - interface和type的区别?
在 TypeScript 中,interface 和 type 都用于定义自定义类型,但它们有一些关键区别:
1. 主要区别
1.1. 语法差异
interface 使用 interface 关键字。
interface Person {
name: string;
age: number;
}
type 使用 type 关键字。
type Person = {
name: string;
age: number;
};
1.2. 扩展方式
interface 使用 extends 扩展。
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
type 使用交叉类型 & 扩展。
type Animal = {
name: string;
};
type Dog = Animal & {
breed: string;
};
1.3. 合并声明
interface 支持声明合并,相同名称的接口会自动合并。
interface User {
name: string;
}
interface User {
age: number;
}
// 最终 User 包含 name 和 age
type 不允许重复声明,会报错
2. 功能差异
2.1. type 能做而 interface 不能的
定义基本类型别名。
type ID = string | number;
定义元组类型。
type Point = [number, number];
使用 typeof 获取实例类型。
const person = { name: 'Alice', age: 30 };
type Person = typeof person;
2.2. interface 的优势
1. 更好的错误提示信息(通常更清晰);
2. 更适合面向对象编程,特别是与类一起使用时;
3. 声明合并特性在某些场景下非常有用(如扩展第三方库类型);
3. 使用建议
1. 优先使用 interface,除非需要 type 的特定功能;
2. 需要联合类型、元组或映射类型时使用 type;
3. 需要扩展第三方类型或需要声明合并时使用 interface;
4. 在库或公共 API 定义中使用 interface,因为它更易扩展;
两者在大多数情况下可以互换,选择主要取决于具体需求和团队约定。