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

相关推荐
灵感__idea1 天前
Hello 算法:“走一步看一步”的智慧
前端·javascript·算法
吴文周1 天前
告别重复劳动:一套插件让 AI 替你写代码、修Bug、做测试、上生产
前端·后端·ai编程
Mh1 天前
我决定写一个 3D 地球仪来记录下我要去的地方
前端·javascript·动效
yaoxin5211231 天前
390. Java IO API - WatchDir 示例
java·前端·python
懒狗小前端1 天前
做了一个 codex 的中文文档网站,做的不好可以随便喷
前端·后端
. . . . .1 天前
ref、useRef 和 forwardRef
前端·javascript·react.js
energy_DT1 天前
2026年海上钻井平台数字孪生平台:引领海洋能源数字化转型
前端
Eric_见嘉1 天前
在职前端 Agent 配置分享
前端·后端·agent
柚子8161 天前
break跳出语句块的神奇技巧
前端·javascript
ejinxian1 天前
Rust GUI框架Azul与Electron、WebView2
前端·javascript·electron