TypeScript 中 Type 和 Interface 有什么区别?

摘要:type 是 类型别名,给一些类型的组合起别名,这样能够更方便地在各个地方使用。假设我们的业务中,id 可以为字符串或数字,那么我们可以定义这么一个名为 ID 的 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,因为它扩展起来会更方便,提示也更友好。 & 真的很难用。

来自:https://www.toutiao.com/article/7136213367198401058/

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_12078