介绍
在TypeScript中,我们不能继承或扩展多个类,但 Mixins有助于我们绕过这一点。
混合物创建部分类,我们可以将它们合并成一个包含部分类所有方法和属性的单一类。
<$>[注]
注: 文档将本教程中的方法描述为替代模式
。
在本教程中,您将创建和使用TypeScript中的混合。
了解班级的限制
让我们创建一个例子,以便我们可以证明混合物的价值。
考虑两个类,‘汽车’和‘Lorry’,分别包含‘驱动’和‘携带’方法,然后考虑一个名为‘卡车’的第三类。
1[label app.ts]
2export class Car {
3 drive(name:string) {
4 console.log(`This ${name} can drive very fast`);
5 }
6}
7
8export class Lorry {
9 carry(weight:number) {
10 console.log(`This vehicle can carry ${weight} kg`);
11 }
12}
13
14export class Truck extends Car, Lorry {}
这不会起作用,因为我们只能扩展一个类。
1[secondary_label Output]
2error: Classes can only extend a single class
为了解决这个问题,我们可以使用混合物。
理解界面类扩展和声明合并
要创建一个混合,我们将利用TypeScript的两个功能:
界面类扩展
与类不同, 界面可以在 TypeScript 中扩展多个类。
1[label app.ts]
2interface A extends ClassB, ClassC {}
当接口扩展一个类时,它只扩展了类成员,而不是他们的实现,因为接口不包含实现。
合并声明
当两个或多个声明以相同的名称声明时, TypeScript将它们合并为一个。
1[label app.ts]
2interface Alligator {
3 eyes: number;
4 nose: number;
5}
6
7interface Alligator {
8 tail: number;
9}
10
11const gator: Alligator = {
12 eyes: 2,
13 nose: 1,
14 tail: 1
15};
gator
包含来自两个Alligator
接口的属性。
使用辅助函数
通过利用TypeScript中的这两种功能,我们可以创建一个与Truck
相同的界面,并扩展Car
和Lorry
类:
1[label app.ts]
2export class Truck {}
3export interface Truck extends Car, Lorry {}
由于 声明合并,卡车
类将与卡车
接口合并,这意味着卡车
类现在将包含来自汽车
和劳瑞
类的函数定义。
为了使卡车
类能够实现从汽车
和Lorry
继承的函数,我们将使用 TypeScript 文档中的辅助函数。
该函数采用了我们要复制实现的第一个参数(在我们的情况下是卡车
)的类的名称,并采用了我们希望复制实现的第二个参数(在我们的情况下是汽车
和Lorry
)的类的集合。
1[label app.ts]
2// the helper function
3function applyMixins(derivedCtor: any, constructors: any[]) {
4 constructors.forEach((baseCtor) => {
5 Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
6 Object.defineProperty(
7 derivedCtor.prototype,
8 name,
9 Object.getOwnPropertyDescriptor(baseCtor.prototype, name) ||
10 Object.create(null)
11 );
12 });
13 });
14}
这就是它是如何使用的:
1[label app.ts]
2applyMixins(Truck, [Car, Lorry]);
我们现在可以从卡车
对象访问汽车
和Lorry
中的方法。
1[label app.ts]
2const truck = new Truck();
3truck.drive("truck");
4truck.carry(10);
此代码将产生以下输出:
1[secondary_label Output]
2This truck can drive very fast
3This vehicle can carry 10 kg
这个卡车
可以访问驱动( )
和携带( )
。
结论
在本教程中,您在TypeScript中创建和使用混合。
从这里,了解 如何为接口使用TypeScript声明合并。