type 和 interface有啥区别嘛
来源:3-9 接口 - 接口初探

慕斯3049357
2019-05-05
type IPeople = {
name: string;
age: number;
}
interface IPeople {
name: string;
age: number;
}
写回答
1回答
-
type 是定义类型别名的关键字,通常用于定义联合类型,交叉类型,原始类型等等,比如课程中 ts-axios 中对 Method 类型定义就用了 type 关键字,而接口不可以。
接口可以合并,比如定义多个同名接口它们会合并到一个,而 type 不可以。
因此,通常我们描述对象的单个数据结构可以用 interface,如果描述的对象有多种数据结构的可能,我们可以定义多个接口用联合类型,然后用 type 给这个联合类型定义一个别名。
举个例子:
interface Dog {
wong()
}
interface Cat {
miao()
}
type Pet = Dog | Cat212019-05-05
相似问题