在 TypeScript 中,interface 和 type 都用来定义自定义类型。它们有一些相似之处,但也有一些区别。
interface 使用 interface 关键字来定义,而 type 使用 type 关键字来定义。// interface 的定义方式interface Person {name: string;age: number;}// type 的定义方式type Person = {name: string;age: number;}合并声明:当多次定义同一个 interface 名称时,会自动合并声明,而对于 type 则会报错。// interface 的合并声明interface Person {name: string;}interface Person {age: number;}// type 的合并声明会报错type Person = {name: string;}type Person = {age: number;}可以实现和继承的能力:interface 可以被类实现,也可以被其他接口继承,而 type 不具备这些能力。// interface 的实现和继承interface Animal {name: string;eat(): void;}class Dog implements Animal {name: string;eat(): void {console.log('Dog is eating.');}}// interface 的继承interface Person {name: string;age: number;}interface Employee extends Person {position: string;}// type 不能实现和继承可以使用交叉类型:interface 可以通过交叉类型表示多个类型的组合,而 type 不能。// interface 的交叉类型interface A {name: string;}interface B {age: number;}type AB = A & B;// type 不支持交叉类型综上所述,interface 适用于定义对象的结构,可以被类实现和其他接口继承,可以定义交叉类型;而 type 则提供了更强大的类型操作能力,比如联合类型、交叉类型、类型别名,但不支持类实现和接口继承。在大多数情况下,可以根据具体需求选择使用 interface 还是 type。