最近在学习 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'
};