TypeScript 中 type 与 interface 的区别

作者:vkvi 来源:ITPOW(原创) 日期:2019-11-29

在某些场合,我们发现,把 type 换成 interface 也没有出错,说明二者在一定程度上具有通用性。

比如:type、interface 内部都可以为属性指定类型,或者为属性指定固定值。

再比如,都可以使用逗号、分号。

不同点

语法不同

type 要等号。type I = {}、interface I {}。

interface 可以使用 extends,type 不行。

interface 可以拆成多部分写,type 不行。

type 可以使用交叉类型联合类型等,interface 不行。

type 可以使用 & 实现 interface 的扩展功能,但是像 |、基础类型别名,这些 interface 无法实现。

相关文章