interface和type关键字的区别
interface:
- 1.同名interface自动聚合。注:与interface同名的class也会自动聚合
- 2.只能声明object,function类型,可聚合和继承class
type:
- 1.type不能自动聚合,因为type声明不能重名
- 2.type不仅仅能够声明 object、class、function
- 3.type支持复杂的类型操作
共同点:都是声明变量类型的方法。
注:就声明这个功能来说,class也可以声明类型,但是typescript所有类型声明的信息都会在编译后清除。class声明编译后依然存在,如果声明只是类型信息,请使用interface和type。(这里多插一句,后续会详细讲解class和interface的具体区别)
Objects/Functions
interface:
interface Person {
name: string;
age: number;
}
interface SetPerson {
(name: string, age: number): void;
}
type:
type Person = {
name: string;
age: number;
}
type SetPerson = (name: string, age: number) => void;
interface和type都能声明Objcet/Function,只是语法不同而已
其他数据类型
interface只能声明Objcet/Function,type还可以声明其他类型,比如:基本数据类型、联合类型、交叉类型、元组等
type Name = string;
type PersonName = {
name: string
};
type PersonAge = {
age: number
}
//联合类型
type Person = PersonName & PersonAge;
//交叉类型
type PersonNameOrPersonAge = PersonName | PersonAge;
//具体定义数组每个元素数据类型
type DateArr = [number, string, boolean];
extend
interface和type都能可以被继承,唯一区别还是语法。
注:interface和type不互斥,可以相互继承,还有一点联合类型不能被实现和集成(implements/extends)。
interface extends interface
interface PersonName {
name: string;
};
interface Person extends PersonName {
age: number;
}
type extends type
type PersonName = {
name: string;
};
type Person = PersonName & { age: number }
interface extends type
type PersonName = {
name: string;
};
interface Person extends PersonName {
age: number;
};
type extends interface
interface PersonName {
name: string;
};
type Person = PersonName & { age: number }
implements
class可以implements interface和type,但是class不能implements/extends联合类型type(联合类型不确定性原因导致),所以使用implements/extends需要注意。
interface Person {
name: string;
age: number;
}
class SomePerson implements Person {
name: '张三';
age: 18;
}
type Person2 = {
name: string;
age: number;
};
class SomePerson2 implements Person2 {
name: '张三';
age: 18;
}
type PartialPerson = { name: string; } | { age: number; };
// ERROR: FIXME: can not implement a union type
class SomePartialPerson implements PartialPerson {
name: '张三';
age: 18;
}
声明合并
interface可以,type不行。
注:interface和type声明变量名不能存在重复冲突。
interface Person {
name: string;
};
interface Person {
age: number;
};
class Person {
sex: string
}
//与interface同名的class也会自动聚合
const person: Person = {
name: '张三',
age: 18,
sex: '男',
}
总结
在实际开发中,如果不明确interface/type使用场景时,能用interface实现的使用interface,不能则使用type。因为type声明的联合类型在implements/extends的时候会编译报错,而interface不存在此问题,因为interface不能声明联合类型。