interfact 与 type 的区别及使用方法
一、 interfact 与 type主要区别
二、 interfact 与 type具体用法
1. 定义对象类型
interface
的典型用法:
interface Person {
name: string;
age: number;
greet(): void;
}
type
的等效定义:
type Person = {
name: string;
age: number;
greet(): void;
};
2. 扩展(继承)
interface 使用 extends
:
interface Employee extends Person {
salary: number;
}
type
使用交叉类型 &
:
type Employee = Person & {
salary: number;
};
3. 联合类型(仅 type
支持)
type Result = Success | Error; // 联合类型
interface Success { data: string }
interface Error { message: string }
4. 元组类型(仅 type
支持)
type Coordinates = [number, number];
5. 声明合并(仅 interface
支持)
interface User { name: string }
interface User { age: number }
// 最终合并为:
// interface User { name: string; age: number }
6. 复杂类型别名(仅 type
支持)
type StringOrNumber = string | number; // 联合类型
type Callback = (data: string) => void; // 函数类型
type Nullable<T> = T | null; // 泛型别名
三、 interfact 与 type使用场景
1、优先 interface
:的场景
定义对象结构(如 API 响应、组件 Props)。
需要声明合并(如扩展第三方库类型)。
通过 implements 约束类的实现。
2、优先 type
:的场景
定义联合类型、交叉类型、元组等复杂类型。
需要类型别名简化重复代码(如 type ID = string)
。
需要直接操作字面量类型(如 type Status = "success" | "error")
。
四、总结
interface
更适合面向对象的类型设计,强调可扩展性和实现。
type
更灵活,适合定义任意复杂类型,尤其是联合类型或工具类型。
两者在大部分场景下可以互换,但需根据语义和需求选择。
实际开发中,团队可根据规范统一选择,例如默认使用 interface 定义对象,用 type 处理复杂类型。