TS中 type 和 interface 的区别

        最近在学习 Typescript 的过程中,在学习类型概念的时候,为了使得类型的复用,可以使用 type 类型别名以及 interface 来自定义类型,那么他们俩具体有什么区别呢,本文将详细的介绍一下他们的相同点以及不同点

语法差异

让我们首先从语法角度来比较 type 和 interface 的不同之处。在TypeScript中,我们使用 type 关键字来定义一个自定义的类型,而使用 interface 关键字来定义另一种类型。

下面是一个使用 type 定义类型的示例代码:

type Point = {
  x: number;
  y: number;
};

以下是使用 interface 定义类型的示例代码: 

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

对象字面量拓展

一个重要的区别是 interface 支持对象字面量的扩展,而 type 不支持。这意味着我们可以通过多个interface 的合并来定义具有相同属性和方法的类型。

考虑下面的示例,我们使用 interface 来定义一个可移动对象的类型,并通过对象字面量扩展来定义具有额外属性的子类型:

interface Movable {
  x: number;
  y: number;
  move: () => void;
}

interface Flyable extends Movable {
  altitude: number;
}

const airplane: Flyable = {
  x: 0,
  y: 0,
  altitude: 10000,
  move() {
    // ...
  }
};

上述示例中,我们使用 interface 定义了 Movable 和 Flyable 两个类型,Flyable 通过 extends 关键字扩展了 Movable 的属性和方法。 

继承与实现

另一个区别是 interface 可以进行多重继承,而 type 不支持继承其他类型。这使得 interface 在面向对象的开发中特别有用,我们可以定义一个接口并通过继承来扩展它。

下面是一个示例,展示了使用 interface 进行多重继承的情况:

interface Shape {
  color: string;
}

interface Circle extends Shape {
  radius: number;
}

interface NamedShape extends Shape {
  name: string;
}

const redCircle: Circle & NamedShape = {
  color: 'red',
  radius: 10,
  name: 'circle'
};

 

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值