【📒笔记】TypeScript 中的 type 和 interface 的区别

140 阅读1分钟

在 TypeScript 中,typeinterface 都用于定义类型,但它们有一些区别。

  1. type 是用来定义一个具体的类型,而 interface 是用来定义一个对象的结构。
  2. type 可以用于定义联合类型、交叉类型和原始类型的别名,而 interface 不能。
  3. type 允许使用 typeof 操作符来获取变量的类型,而 interface 不支持。
  4. interface 支持继承,可以通过 extends 关键字来扩展其他接口,而 type 不支持继承。

下面是一些示例,展示了 typeinterface 的使用情况:

// 使用 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 取决于你的需求和个人偏好。