type和interface的主要区别

type和interface有什么区别

相同

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

继承(泛化)

interface

typescript 复制代码
interface a { name: string; }
interface b extends a { sex: string; }

type

typescript 复制代码
type a = { name: string; }
type b = a & { sex: string; }

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

interface

typescript 复制代码
interface a {
  (): void; // 普通调用
  (a: string): void; // 重载

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

type

typescript 复制代码
type a = {
  (): void; //普通调用
  (a: string): void; //重载

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

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

最大的不同

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

举个例子

给全局Date对象加个format

typescript 复制代码
interface Date {
  format(template: string): string
} 

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

typescript 复制代码
interface DateConstructor {
  format(template: string): string
}

在线看

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

相关推荐
幼儿园技术家7 分钟前
Uniapp简易使用canvas绘制分享海报
前端
开开心心就好1 小时前
免费PDF处理软件,支持多种操作
运维·服务器·前端·spring boot·智能手机·pdf·电脑
全宝1 小时前
🎨前端实现文字渐变的三种方式
前端·javascript·css
yanlele1 小时前
前端面试第 75 期 - 2025.07.06 更新前端面试问题总结(12道题)
前端·javascript·面试
妮妮喔妮2 小时前
【无标题】
开发语言·前端·javascript
谦行2 小时前
深度神经网络训练过程与常见概念
前端
Simon_He2 小时前
一个免费的在线压缩网站超越了付费的压缩软件
前端·开源·图片资源
巴巴_羊3 小时前
React Ref使用
前端·javascript·react.js
拾光拾趣录3 小时前
CSS常见问题深度解析与解决方案(第三波)
前端·css
轻语呢喃3 小时前
JavaScript :字符串模板——优雅编程的基石
前端·javascript·后端