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的一个区别。

相关推荐
编程社区管理员4 小时前
React 发送短信验证码和验证码校验功能组件
前端·javascript·react.js
全马必破三4 小时前
React“组件即函数”
前端·javascript·react.js
三思而后行,慎承诺5 小时前
React 底层原理
前端·react.js·前端框架
座山雕~5 小时前
html 和css基础常用的标签和样式
前端·css·html
灰小猿5 小时前
Spring前后端分离项目时间格式转换问题全局配置解决
java·前端·后端·spring·spring cloud
im_AMBER6 小时前
React 16
前端·笔记·学习·react.js·前端框架
02苏_6 小时前
ES6模板字符串
前端·ecmascript·es6
excel6 小时前
⚙️ 一次性警告机制的实现:warnOnce 源码深度解析
前端
excel6 小时前
Vue SFC 样式编译核心机制详解:compileStyle 与 PostCSS 管线设计
前端
excel6 小时前
🧩 使用 Babel + MagicString 实现动态重写 export default 的通用方案
前端