1. 写法上
type
使用关键字 type 进行声明。
interface
使用关键字 interface 进行声明。
// 使用 type
type MyType = {
param: string;
};
// 使用 interface
interface MyInterface {
param: string;
}
2. 可合并性
interface
具有可合并性,允许在同一作用域内多次声明同名的接口,这些声明将会合并为一个接口。
type
不具有可合并性,如果多次声明同名的类型,会报错。
// interface 具有可合并性
interface MyInterface {
param: string;
}
interface MyInterface {
additionParam: number;
}
// 最终合并后的接口
// { param: string; additionParam: number; }
3. 拓展性
interface
支持接口的扩展(extends
关键字)。
type
支持联合类型和交叉类型,但不能使用 extends关键字 进行扩展。
// 使用 interface 扩展
interface ExtendedInterface extends MyInterface {
newParam: string;
}
// 使用 type 交叉类型
type ExtendedType = MyType & {
newParam: string};
4. 接口的实现
class
可以用implements
实现一个接口。
type 不能被类实现。
// 使用 interface 实现
interface MyInterface {
prop: string;
}
class MyClass implements MyInterface {
prop = "value";
}
5. 使用场景
一般来说,interface
更适合声明一个对象。
interface Person {
name: string;
age: number;
greet(): void;
}
const person: Person = {
name: 'John',
age: 30,
greet() {
console.log('Hello!');
}
};
type
更适合表示联合类型、交叉类型和其他高级类型,创建类型别名。
type Status = 'success' | 'error';
type Coordinate = {
x: number;
y: number;
};
type Point3D = Coordinate & {
z: number };
type FunctionType<T> = (arg: T) => void;