在 TypeScript 中,可以通过 interface extends 和 type & type(交叉类型)来扩展(继承)类型。接口也可以扩展类型,反之亦然。
接口使用关键字 extends 来继承属性:
interface Animal { name: string; } interface Bird extends Animal { wings: number; }
类型可以通过 & 来组合:
type Animal = { name: string }; type Bird = Animal & { wings: number };
另外,接口可以扩展另一个类型:
type Base = { id: number }; interface Derived extends Base { description: string; }
特点:
可以通过接口扩展类型,或者反过来吗?大多数人犯了什么错误?
许多人认为只能通过接口扩展接口,但实际上,接口可以扩展类型:
type Basic = { flag: boolean }; interface Extra extends Basic { name: string; }
但类型不能通过 extends 扩展其他类型 — 只能通过交叉类型(&)。
故事
故事
故事
团队认为接口不能通过类型扩展,因此为了扩展通用功能,重写了所有结构,从 type 变为 interface,花费了大量时间和精力 — 而实际上可以以非标准方式扩展现有类型。