大家好,我是前端西瓜哥,今天我们来看看 type 和 interface 的区别。
type 是 类型别名,给一些类型的组合起别名,这样能够更方便地在各个地方使用。
假设我们的业务中,id 可以为字符串或数字,那么我们可以定义这么一个名为 ID 的 type:
复制
type ID = string | number;
1.
定义一个名为 Circle 的对象结构 type:
复制
type Circle = { x: number; y: number; radius: number; }
1.
2.
3.
4.
5.
interface 是 接口。有点像 type,可以用来代表一种类型组合,但它范围更小一些,只能描述对象结构。
复制
interface Position { x: number; y: number; }
1.
2.
3.
4.
它们写法有一点区别,type 后面需要用 =,interface 后面不需要 =,直接就带上 {。
type 能表示的任何类型组合。
interface 只能表示对象结构的类型。
interface 可以继承(extends)另一个 interface。
下面代码中,Rect 继承了 Shape 的属性,并在该基础上新增了 width 和 height 属性。
复制
interface Shape { x: number; y: number; }// 继承扩展interface Rect extends Shape { width: number; height: number; }const rect: Rect = { x: 0, y: 0, width: 0, height: 0 };
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
interface 也可以继承自 type,但只能是对象结构,或多个对象组成交叉类型(&)的 type。
再来看看 type 的继承能力。
type 可以通过 & 的写法来继承 type 或 interface,得到一个交叉类型:
复制
type Shape = {x: number;y: number; }type Circle = Shape & { r: number }const circle: Circle = { x: 0, y: 0, r: 8 }
1.
2.
3.
4.
5.
6.
interface 支持声明合并,文件下多个同名的 interface,它们的属性会进行合并。
复制
interface Point { x: number; }interface Point { y: number; }const point: Point = { x: 10, y: 30 };
1.
2.
3.
4.
5.
6.
7.
需要注意的是,同名属性的不能进行类型覆盖修改,否则编译不通过。比如我先声明属性 x 类型为 number,然后你再声明属性 x 为 string | numebr,就像下面这样,编译器会报错。
复制
interface Point { x: number; }interface Point { // 报错 // Property 'x' must be of type 'number', but here has type 'string | number'. x: string | number; y: number; }
1.
2.
3.
4.
5.
6.
7.
8.
9.
extends 可以将属性的类型进行收窄,比如从 string | number 变成 string。
但声明合并不行,类型必须完全一致。
type 不支持声明合并,一个作用域内不允许有多个同名 type。
复制
// 报错:Duplicate identifier 'Point'. type Point = { x: number; } // 报错:Duplicate identifier 'Point'. type Point = { y: number; }
1.
2.
3.
4.
5.
6.
7.
8.
当然,如果有和 type 同名的 interface,也会报错。
总结一下,type 和 interface 的不同点有:
type 后面有 =,interface 没有。
type 可以描述任何类型组合,interface 只能描述对象结构。
interface 可以继承自(extends)interface 或对象结构的 type。type 也可以通过 &做对象结构的继承。
多次声明的同名 interface 会进行声明合并,type 则不允许多次声明。
大多数情况下,我更推荐使用 interface,因为它扩展起来会更方便,提示也更友好。& 真的很难用。