对typescript 有一定了解的,会发现 interface 和 type 很相似,类型定义上,很多时候,用两种方式都能实现。

三分钟直入主题, 除了语法不同外,interface和type主要有区别

1 类型别名可以用于其它类型 (联合类型、元组类型、基本类型(原始值)),interface不支持

type PartialPointX = { x: number };
type PartialPointY = { y: number };

// union(联合)
type PartialPoint = PartialPointX | PartialPointY;

// tuple(元祖)
type Data = [PartialPointX, PartialPointY];

//primitive(原始值)
type Name = Number;

// typeof的返回值
let div = document.createElement('div');
type B = typeof div;

2 interface 可以多次定义 并被视为合并所有声明成员 type 不支持

interface Point {
  x: number;
}
interface Point {
  y: number;
}

const point: Point = { x: 1, y: 2 };

3 type 能使用 in 关键字生成映射类型,但 interface 不行。

type Keys = 'firstname' | 'surname';

type DudeType = {
  [key in Keys]: string;
};

const test: DudeType = {
  firstname: 'Pawel',
  surname: 'Grzybek',
};

4 默认导出方式不同

// inerface 支持同时声明,默认导出 而type必须先声明后导出
export default interface Config {
  name: string;
}
// 同一个js模块只能存在一个默认导出哦
 type Config2 = {name: string}
  export default Config2

本文转自 https://blog.csdn.net/glorydx/article/details/112625953,如有侵权,请联系删除。

 

https://zhuanlan.zhihu.com/p/453701771

https://developer.51cto.com/article/703803.html

posted on   ygunoil  阅读(829)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
历史上的今天:
2019-07-25 js中的生成器函数
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示