Interface vs Type
· 阅读需 2 分钟
比较Interface,Type的差异
写法的不同
interface Person {
name: string,
age:number,
saySomething(text:string):void
}
type Student = {
name:string,
age:number,
saySomething(text:string):void
}
适用范围
type作为类型别名能够用于基本数据类型、联合类型、元组,
而interface做不到
// primitive
type Name = string;
// object
type PartialPointX = { x: number; };
type PartialPointY = { y: number; };
// union
type PartialPoint = PartialPointX | PartialPointY;
// tuple
type Data = [number, string];
// dom
let div = document.createElement('div');
type B = typeof div;
定义
与类型别名不同,接口可以定义多次,会被自动合并为单个接口。
interface Point { x: number; }
interface Point { y: number; }
const point: Point = { x: 1, y: 2 };
拓展
两者的扩展 方式不同,但并不互斥。接口可以扩展类型别名,同理,类型别名也可以扩展接口。
接口的扩展就是继承,通过 extends 来实现。类型别名的扩展就是交叉类型,通过 & 来实现
//类型别名拓展类型别名
type PointX = {
x: number
}
type Point = PointX & {
y: number
}
//接口拓展接口
interface PointX {
x: number
}
interface Point extends PointX {
y: number
}
//类型别名拓展接口
interface PointX {
x: number
}
type Point = PointX & {
y: number
}
//接口拓展类型别名
type PointX = {
x: number
}
interface Point extends PointX {
y: number
}
