likes
comments
collection
share

type和interface的主要区别

作者站长头像
站长
· 阅读数 81

type和interface有什么区别

相同

实际上如果只用于标明类型的话,type基本可以实现interface的所有功能

继承(泛化)

interface

interface a { name: string; }
interface b extends a { sex: string; }

type

type a = { name: string; }
type b = a & { sex: string; }

标明函数类型以及函数重载

interface

interface a {
  (): void; // 普通调用
  (a: string): void; // 重载

  new(): Date; // 构造函数
}

type

type a = {
  (): void; //普通调用
  (a: string): void; //重载

  new(): Date; // 构造函数
}

// 或者这样写构造函数
type a = new () => Date;

最大的不同

但是interface强大的地方就在于,它可以扩展全局对象,当然这也与interface合并特性有关。也是和type的主要区别。

举个例子

给全局Date对象加个format

interface Date {
  format(template: string): string
} 

type和interface的主要区别

当然如果你想给Date构造函数添加一个format

interface DateConstructor {
  format(template: string): string
}

type和interface的主要区别

在线看

当然interface作为接口的话,那还有一个特性就是implements之后,必须被实现。这也是和type的一个区别。

转载自:https://juejin.cn/post/7296665348572938291
评论
请登录