2.type 和 interface
wabicai
# 2.type 和 interface
首先,很多人都用 type 和 interface 用来比较,但是这是不对的,因为他们的含义就不一样。
type 在官网,叫做 type alias,是类型别名。就是说,一个类型的另外一个名称。他跟类型没有任何关系。
interface 是接口,是一个对象的形状,就是说,一个对象的属性和方法的集合,他就是一个类型。
# 主要的区别
- 接口 interface 是通过继承的方式来扩展,类型别名 type 是通过 & 来扩展。
- 接口可以自动合并,而类型别名不行。(因为一个别名,不能有多个实例)
# 建议
- 能用 interface 就用 interface。并且对于接口,可以加 I 作为前缀。
# 实战
# 继承
interface father {}
interface extends father {}
1
2
2
- type 不支持继承, 是使用另一种方式。交叉类型 &
type Student = Person & {grade:number}- 即:interface 用 extends 继承,type 用交叉类型实现继承
# 定义接口成员
- interface 必须显示提供所有声明和方法
- type 不需要
- 所以 interface 用来定义复杂的数据结构
- type 是别名,用来定义简单的数据格式
# 类型重载
- 类型重载可以用于函数,传入不同类型,传出的值也不同的时候。
interface Person {
name: string;
}
interface Person {
// 重复声明 interface,就合并了
age: number;
}
const person: Person = {
name: "lin",
age: 18,
};
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
- type 不行