在 TypeScript 中,type
和 interface
都用于定义类型,但它们在使用场景和功能上存在一些关键区别。以下是它们的详细对比:
1. 基本定义
-
interface
:- 主要用于定义 对象的结构(属性和方法)。
- 支持 声明合并(多次声明同一接口会自动合并)。
- 通过
extends
实现继承。
interface Person { name: string; age: number; }
-
type
:- 可以为任何类型(包括原始类型、联合类型、交叉类型等)定义别名。
- 不支持声明合并。
- 通过
&
实现交叉类型扩展。
type Age = number; type Person = { name: string; age: Age; };
2. 主要区别
特性 | interface | type |
---|---|---|
声明合并 | ✅ 支持 | ❌ 不支持 |
扩展方式 | extends 关键字 | 交叉类型 & |
适用类型 | 只能定义对象类型 | 可定义任何类型(对象、联合、元组等) |
实现类 | 可通过 implements 实现 | 只能实现对象类型的 type |
工具提示 | 显示接口名称(更清晰) | 显示别名展开后的类型(可能冗长) |
联合/交叉类型 | 需通过继承组合 | 直接支持联合(` |
3. 使用场景
推荐使用 interface
- 定义对象类型:
interface User {
id: string;
name: string;
}
- 需要声明合并(如扩展第三方库类型):
interface Window {
myCustomProp: string;
}
- 类实现接口:
interface Animal {
eat(): void;
}
class Dog implements Animal {
eat() { /* ... */ }
}
推荐使用 type
- 定义联合类型:
type Result = Success | Failure;
- 定义交叉类型:
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
- 定义元组或复杂类型:
type Coordinates = [number, number];
type Callback = (data: string) => void;
- 使用条件类型或映射类型:
type Nullable<T> = T | null;
type ReadonlyUser = Readonly<User>;
4. 示例对比
扩展类型
interface
(使用extends
):interface Animal { name: string } interface Dog extends Animal { breed: string }
type
(使用&
):type Animal = { name: string }; type Dog = Animal & { breed: string };
联合类型
type
(interface
无法直接实现):type ID = string | number;
5. 最佳实践
- 默认使用
interface
:
当需要定义对象类型或需要声明合并时,优先使用interface
。 - 使用
type
的场景:
当需要定义联合、交叉类型,或使用高级类型工具(如条件类型、映射类型)时,使用type
。
总结
interface
:
适合定义对象结构,支持声明合并和类实现,代码可读性高。type
:
灵活,支持任何类型定义,适合复杂类型操作。
根据具体需求选择合适的关键字,可以使代码更清晰、可维护性更高。