Tutorial

TypeScript Mixins

Updated on September 1, 2021
Default avatar

By Alfred M. Adjei

TypeScript Mixins

Introduction

In TypeScript, we can’t inherit or extend from more than one class, but Mixins helps us to get around that.

Mixins create partial classes that we can combine to form a single class that contains all the methods and properties from the partial classes.

Note: The documentation describes the approach in this tutorial as an “Alternative Pattern”.

In this tutorial, you will create and use mixins in TypeScript.

Understanding the Limitations of Classes

Let’s create an example so that we can demonstrate the value of mixins.

Consider two classes, Car and Lorry, which contain the drive and carry methods respectively. Then, consider a third class called Truck. A Truck should include both drive and carry methods:

app.ts
export class Car {
  drive(name:string) {
    console.log(`This ${name} can drive very fast`);
  }
}

export class Lorry {
  carry(weight:number) {
    console.log(`This vehicle can carry ${weight} kg`);
  }
}

export class Truck extends Car, Lorry {}

This will not work because we can only extend a single class.

Output
error: Classes can only extend a single class

To solve this, we can use mixins.

Understanding Interface Class Extension and Declaration Merging

To create a mixin, we’ll take advantage of two functionalities of TypeScript:

Interface class extension

Unlike classes, interfaces can extend multiple classes in TypeScript.

app.ts
interface A extends ClassB, ClassC {}

When an interface extends a class, it extends only the class members but not their implementation because interfaces don’t contain implementations.

Declaration merging

When two or more declarations are declared with the same name, TypeScript merges them into one.

app.ts
interface Alligator {
  eyes: number;
  nose: number;
}

interface Alligator {
  tail: number;
}

const gator: Alligator = {
  eyes: 2,
  nose: 1,
  tail: 1
};

gator contains properties from both Alligator interfaces.

Using the Helper Function

By leveraging these two functionalities in TypeScript, we can create an interface with the same name as Truck and extend both the Car and Lorry classes:

app.ts
export class Truck {}
export interface Truck extends Car, Lorry {}

Due to declaration merging, the Truck class will be merged with the Truck interface. This means that the Truck class will now contain the function definitions from both Car and Lorry classes.

To enable the Truck class to implement the functions inherited from Car and Lorry, we’ll use a helper function found in the TypeScript docs.

The function takes the name of the class to which we want to copy the implementations as the first argument (which in our case is Truck) and takes an array of classes from which we want to copy the implementations as the second argument (which in our case is Car and Lorry).

app.ts
// the helper function
function applyMixins(derivedCtor: any, constructors: any[]) {
  constructors.forEach((baseCtor) => {
    Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
      Object.defineProperty(
        derivedCtor.prototype,
        name,
        Object.getOwnPropertyDescriptor(baseCtor.prototype, name) ||
          Object.create(null)
      );
    });
  });
}

And here’s how it’s used:

app.ts
applyMixins(Truck, [Car, Lorry]);

We can now access the methods in Car and Lorry from a truck object.

app.ts
const truck = new Truck();
truck.drive("truck");
truck.carry(10);

This code will produce the following output:

Output
This truck can drive very fast This vehicle can carry 10 kg

This truck can access drive() and carry().

Conclusion

In this tutorial, you created and used mixins in TypeScript.

From here, learn How To Use TypeScript Declaration Merging for Interfaces.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alfred M. Adjei

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel