interface和type的区别

228 阅读2分钟

在 TypeScript 中,interfacetype 都用于定义自定义类型,但它们之间存在一些区别:

  1. 语法:

    • interface:使用 interface 关键字定义,
    • 例如 interface Person { name: string; age: number; }
    • type:使用 type 关键字定义,
    • 例如 type Person = { name: string; age: number; }
  2. 对象类型和函数类型的定义:

    • interface:可以用来定义对象类型,也可以定义函数类型。
    • type:可以用来定义对象类型,也可以定义函数类型。
  3. 合并(Merging):

    • interface:可以通过同名的 interface 声明进行合并。
    • type:可以通过同名的 type 声明进行合并。
  4. 实现(Implementation)和继承(Extending):

    • interface:可以通过 implements 关键字来实现(implement)一个接口,类似于面向对象编程中的接口实现。可以通过 extends 关键字来继承(extend)一个接口,从而扩展接口的属性和方法。
    • type:无法直接实现或继承。
  5. 扩展类型(Intersection & Union):

    • interface:可以使用交叉类型(Intersection)合并多个接口,使用联合类型(Union)定义一个属性可以拥有多种类型。
    • type:可以使用交叉类型(Intersection)合并多个类型,使用联合类型(Union)定义一个属性可以拥有多种类型。

总体来说,interface 在定义对象类型和函数类型时更常用,并且具有更多面向对象编程的特性,如实现和继承。type 更加灵活,可以定义对象类型、函数类型,以及进行类型的交叉和联合。在选择使用 interface 还是 type 时,可以根据具体需求和个人偏好来决定。通常,如果需要使用面向对象编程的特性,如实现和继承,可以选择 interface;如果需要更灵活的类型定义,可以选择 type