最近做项目用的是 ant design
, 正好也是用 ts
写的, 就顺便看了看源码。结果发现有些类型声明还用了 type
来写(这是什么鬼), 于是赶紧google一下, 搁这里记录一手
refer: stackoverflow: typescript-interfaces-vs-types
Q: 在 typescript 中, 我们定义类型有两种方式: 接口(interface) 和类型别名(type alias)1
2
3
4
5
6
7
8
9
10
11interface Child {
name?: string;
age?: number;
hobby?: Array<string>;
}
type Child = {
name?: string;
age?: number;
hobby?: Array<string>;
}
这两种定义方式有什么区别?
A: 在官方文档中我们可以看到:
Unlike an interface declaration, which always introduces a named object type, a type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types.
不同于 interface 只能定义对象类型, type 声明的方式可以定义组合类型,交叉类型,原始类型。
但如果用 type alias
声明的方式,会导致一些功能的缺失:
example:
1 | interface C { |