在 TypeScript 中,type 和 interface 都用于定义类型,但它们有一些区别。
type是用来定义一个具体的类型,而interface是用来定义一个对象的结构。type可以用于定义联合类型、交叉类型和原始类型的别名,而interface不能。type允许使用typeof操作符来获取变量的类型,而interface不支持。interface支持继承,可以通过extends关键字来扩展其他接口,而type不支持继承。
下面是一些示例,展示了 type 和 interface 的使用情况:
// 使用 type 定义一个别名
type Age = number;
type Name = string;
// 使用 interface 定义一个对象结构
interface Person {
name: string;
age: number;
}
// 使用 type 定义联合类型
type Status = 'active' | 'inactive';
// 使用 interface 定义继承
interface Employee extends Person {
designation: string;
}
// 使用 type 定义交叉类型
type Admin = Person & { isAdmin: boolean };
总结来说,type 更适合用于定义具体的类型别名、联合类型和交叉类型,而 interface 更适合用于定义对象的结构和支持继承。在实际使用中,选择使用 type 还是 interface 取决于你的需求和个人偏好。