TypeScript 中 Type 和 Interface 有什么区别?

开发 前端
今天我们来看看 Type 和 Interface 的区别。Type 是 类型别名,给一些类型的组合起别名,这样能够更方便地在各个地方使用。Interface 是 接口。有点像 type,可以用来代表一种类型组合,但它范围更小一些,只能描述对象结构。

大家好,我是前端西瓜哥,今天我们来看看 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 的不同点有:

  1. type 后面有 =,interface 没有。
  2. type 可以描述任何类型组合,interface 只能描述对象结构。
  3. interface 可以继承自(extends)interface 或对象结构的 type。type 也可以通过 &做对象结构的继承。
  4. 多次声明的同名 interface 会进行声明合并,type 则不允许多次声明。

大多数情况下,我更推荐使用 interface,因为它扩展起来会更方便,提示也更友好。& 真的很难用。

责任编辑:姜华 来源: 今日头条
相关推荐

2022-03-13 18:53:31

interfacetypeTypeScript

2022-05-06 09:21:21

TypeScriptinterfacetype

2021-06-23 08:01:18

TypeScript interface type

2022-08-31 08:33:54

Bash操作系统Linux

2019-04-03 14:16:25

Type 1Type 2虚拟机

2021-08-05 08:32:45

TypeScript InterfaceType

2021-03-27 10:56:17

promisethenfinally

2020-03-09 20:56:19

LoRaLoRaWAN无线技术

2022-09-07 18:32:57

并发编程线程

2020-11-09 14:07:53

PyQtQt编程

2022-06-06 14:53:02

LoRaLoRaWAN

2022-09-08 18:38:26

LinuxWindowsmacOS

2022-08-02 08:23:37

SessionCookies

2022-02-27 15:33:22

安全CASBSASE

2021-12-17 14:40:02

while(1)for(;;)语言

2021-05-16 14:26:08

RPAIPACIO

2024-03-05 18:59:59

前端开发localhost

2020-08-02 23:20:36

JavaScriptmap()forEach()

2020-09-23 09:08:05

typescript

2023-11-01 08:08:47

PythonIS运算符
点赞
收藏

51CTO技术栈公众号