类型有点像接口,反之亦然: 两者都可以由类实现。
但它们之间有一些重要的区别:
1.当 Type 由类实现时,属于 Type 的属性必须在类内初始化,而使用 Interface 必须声明它们。
正如@ryan 提到的: 接口可以扩展另一个接口,而类型不能。
type Person = {
name:string;
age:number;
}
// must initialize all props - unlike interface
class Manager implements Person {
name: string = 'John';
age: number = 55;
// can add props and methods
size:string = 'm';
}
const jane : Person = {
name :'Jane',
age:46,
// cannot add more proprs or methods
//size:'s'
}