当前栏目
TypeScript 中 Type 和 Interface 有什么区别?
大家好,我是前端西瓜哥,今天我们来看看 type 和 interface 的区别。
type 和 interface
type 是 类型别名,给一些类型的组合起别名,这样能够更方便地在各个地方使用。
假设我们的业务中,id 可以为字符串或数字,那么我们可以定义这么一个名为 ID 的 type:
type ID = string | number;
定义一个名为 Circle 的对象结构 type:
type Circle = {
x: number;
y: number;
radius: number;
}
interface 是 接口。有点像 type,可以用来代表一种类型组合,但它范围更小一些,只能描述对象结构。
interface Position {
x: number;
y: number;
}
它们写法有一点区别,type 后面需要用 =,interface 后面不需要 =,直接就带上 {。
范围
type 能表示的任何类型组合。
interface 只能表示对象结构的类型。
继承
interface 可以继承(extends)另一个 interface。
下面代码中,Rect 继承了 Shape 的属性,并在该基础上新增了 width 和 height 属性。
interface Shape {
x: number;
y: number;
}
// 继承扩展
interface Rect extends Shape {
width: number;
height: number;
}
const rect: Rect = { x: 0, y: 0, width: 0, height: 0 };
interface 也可以继承自 type,但只能是对象结构,或多个对象组成交叉类型(&)的 type。
再来看看 type 的继承能力。
type 可以通过 & 的写法来继承 type 或 interface,得到一个交叉类型:
type Shape = {
x: number;
y: number;
}
type Circle = Shape & { r: number }
const circle: Circle = { x: 0, y: 0, r: 8 }
声明合并
interface 支持声明合并,文件下多个同名的 interface,它们的属性会进行合并。
interface Point {
x: number;
}
interface Point {
y: number;
}
const point: Point = { x: 10, y: 30 };
需要注意的是,同名属性的不能进行类型覆盖修改,否则编译不通过。比如我先声明属性 x 类型为 number,然后你再声明属性 x 为 string | numebr,就像下面这样,编译器会报错。
interface Point {
x: number;
}
interface Point {
// 报错
// Property 'x' must be of type 'number', but here has type 'string | number'.
x: string | number;
y: number;
}
extends 可以将属性的类型进行收窄,比如从 string | number 变成 string。
但声明合并不行,类型必须完全一致。
type 不支持声明合并,一个作用域内不允许有多个同名 type。
// 报错:Duplicate identifier 'Point'.
type Point = {
x: number;
}
// 报错:Duplicate identifier 'Point'.
type Point = {
y: number;
}
当然,如果有和 type 同名的 interface,也会报错。
结尾
总结一下,type 和 interface 的不同点有:
- type 后面有 =,interface 没有。
- type 可以描述任何类型组合,interface 只能描述对象结构。
- interface 可以继承自(extends)interface 或对象结构的 type。type 也可以通过 &做对象结构的继承。
- 多次声明的同名 interface 会进行声明合并,type 则不允许多次声明。
大多数情况下,我更推荐使用 interface,因为它扩展起来会更方便,提示也更友好。& 真的很难用。
相关文章
- Spring Boot中的Freemarker模版引擎引用css和js的正确姿势
- Node.js解压版的环境配置及相关常用命令
- JSP学习笔记(6)—— 自定义MVC框架
- JSP学习笔记(5)——Servlet、监听器、过滤器、MVC模式介绍
- Jsp学习笔记(4)——分页查询
- JSP学习笔记(3)——JSTL 标签库
- JSP学习笔记(1)——Jsp指令、动作元素和内置对象
- echarts map地图中绘制浙江省市区县乡镇多级联动边界下钻的最新geojson数据文件获取和更新
- ArcGIS QGIS学习一:打开shp、geojson地图变形变扁问题(附最新坐标边界下载全国省市区县乡镇)
- 从区划边界geojson中查询经纬度坐标对应的省市区县乡镇名称,开源Java工具,内存占用低、高性能
- 全国省市区县和乡镇街道行政区划矢量边界坐标经纬度地图最新数据免费下载 支持shp geojson json sql格式
- 几行代码把Chrome搞崩溃之:HTML5 MP3录音由ScriptProcessorNode升级成AudioWorkletNode采坑记
- JavaScript ES6 Promise对象
- Web前端——JavaScript扩展补充
- Web前端——表单提交和Js添加选项
- Web前端——JavaScript练习
- Web前端——JavaScript笔记
- 从高德采集最新的省市区三级坐标和行政区域边界,用js在浏览器中运行
- 从统计局采集最新的省市区镇数据,用js在浏览器中运行 V2
- 记录一下对swiper4.x.js在H5单页中的滑动优化