当前位置: 首页 > article >正文

type和interface区别

使用 typescript 总会使用到 interface 和 type

相同点:

都可以描述一个对象或者函数

interface

interface User {
  name: string
  age: number
}

interface SetUser {
  (name: string, age: number): void;
}

type

type User = {
  name: string
  age: number
};

type SetUser = (name: string, age: number): void;

拓展(extends)与 交叉类型(Intersection Types)

interface 可以 extends, 但 type 是不允许 extends 和 implement 的,但是 type 却可以通过交叉类型 实现 interface 的 extend 行为,并且两者并不是相互独立的,也就是说 interface 可以 extends type, type 也可以 与 interface 类型 交叉 。

虽然效果差不多,但是两者语法不同

interface extends interface

interface Name { 
  name: string; 
}
interface User extends Name { 
  age: number; 
}

type 与 type 交叉

type Name ={
  name:string
}
type User = Name & {age:number}

type 与interface交叉

type Name = { 
  name: string; 
}
interface User extends Name { 
  age: number; 
}

不同点:

type 可以而 interface 不行

type 可以声明基本类型别名,联合类型,元组等类型

type Name = string

interface Dog = {
  wang()
}
interface Cat = {
  miao()
}

type P = Dog|Cat

// 具体定义数组每个位置的类型
type pList=[Dog,Cat]

type 语句中还可以使用 typeof 获取实例的 类型进行赋值

// 当你想获取一个变量的类型时,使用 typeof
let div = document.createElement('div');
type B = typeof div

其他操作

type StringOrNumber = string | number;  
type Text = string | { text: string };  
type NameLookup = Dictionary<string, Person>;  
type Callback<T> = (data: T) => void;  
type Pair<T> = [T, T];  
type Coordinates = Pair<number>;  
type Tree<T> = T | { left: Tree<T>, right: Tree<T> };

interface 可以而 type 不行

interface 能够声明合并

interface User {
  name: string
  age: number
}

interface User {
  sex: string
}

/*
User 接口为 {
  name: string
  age: number
  sex: string 
}
*/
  • 接口是通过继承的方式来扩展,类型别名是通过 & 来扩展。
  • 接口可以自动合并,而类型别名不行

http://www.kler.cn/news/307722.html

相关文章:

  • redis 十大应用场景
  • 《Effective Debugging:软件和系统调试的66个有效方法》读书笔记-Part2
  • 828华为云征文|华为Flexus云服务器搭建Cloudreve私人网盘
  • 优化Web性能:Varnish中精准识别并缓存移动与桌面请求
  • html+css网页设计 旅游网站首页1个页面
  • WPF入门教学一 WPF简介
  • 【C++前后缀分解 动态规划】2100. 适合野炊的日子|1702
  • ROS笔记3.路径规划1
  • 卸载Linux 内核 以及NVIDIA驱动
  • 【学习归纳自我总结版】尚硅谷学习第一天
  • 1、vectorCast单元测试常用操作
  • 无人机培训机构技术股份合作探讨
  • 数据结构修炼——顺序表和链表的区别与联系?
  • 【C++】STL数据结构最全函数详解2-向量vector
  • EndnoteX9安装及使用教程
  • 腾讯云Ubuntu系统安装宝塔,配置Java环境,运行spring boot项目
  • 系统架构设计师教程 第7章 7.1 软件架构概念 笔记
  • 每日奇难怪题(持续更新)
  • 微生物分类检测系统源码分享
  • SprinBoot+Vue工商局商家管理系统的设计与实现
  • 基于 PyQt5 和 OpenCV 进行图像处理操作的GUI工具初版
  • 初探全同态加密1 —— FHE的定义与历史回顾
  • Linux服务器上安装git lfs命令
  • 《深度学习》深度学习 框架、流程解析、动态展示及推导
  • 【LeetCode】每日一题 2024_9_16 公交站间的距离(模拟)
  • 云原生和非云原生哪个好?六大区别详细对比
  • Python编程 - 线程
  • 源代码审查范围为:
  • 【宠物小精灵之收服(待更新)】
  • leetcode 2398.预算内的最多机器人数目