用了一年Typescript,今天来回顾下interface和type到底有啥区别
- 实际工作中, 我一般经常用的interface,因为拥有更好的扩展性,但是今天回顾了下,type还是有很多痛点的,今后也许我不再会interface一把梭,而是不同情况区分开来
第一点
- type是类型别名,只描述所有数据
- interface 是类型声明,用来描述对象的属性用的
第二点
- type不可重新赋值,
- interface在相同的模块中,相同的interface会自动合并
第三点
- 因为interface可以扩展,所以当我写api的时候,应该使用interface,方便扩展
- type不可扩展 , 所以比如当我在声明函数组件的props时,我不希望有人更改我的props的类型,这时候应该用到type
//interface自动合并
interface A {
name: string;
}
interface A {
age: number;
}
const people: A = {
name: 'jojo',
age: 18,
};
//type不可以自动合并.用在不可扩展严格限制类型的场景中
const useMap = (props: Props) => {
return props;
};
总结
自由扩展?面向对象? 选interface
简单的声明一个严格的类型,或者简单简短的场景?? 那就用type吧
PS:
type也可以用继承,用&符号,更加简约明了,比如下面这个栗子🌰
//interface 的继承
interface A {
name: string;
}
interface B extends A {
age: number;
}
const people: B = {
name: '12',
age: 12,
};
//tpye的继承??
type A = {
name: string;
} & B;
type B = {
age: number;
};
const people: A = {
name: '12',
age: 12,
};