πŸŽ„ Get 50% off from our JavaScript course for the holidays! πŸŽ„

How to Extend Multiple Classes in TypeScript With Mixins

Ferenc Almasi β€’ 2022 September 26 β€’ πŸ“– 2 min read

You cannot extend multiple classes at once using the extends keyword in TypeScript. However, you can use a mixinΒ β€” a special function that can be used for extending multiple classes.

// This will throw an error: "Classes can only extend a single class."
class Tomato extends Vegetable, Fruit { ... }
Extending multiple classes with the extends keyword is not possible
Copied to clipboard!

Whenever you try to extend a class with multiple other classes, you will get the following error: "Classes can only extend a single class.". To resolve this, create the following function in your codebase that you can use for extending multiple classes:

const applyMixins = (baseClass: any, extendedClasses: any[]) => {
    extendedClasses.forEach(extendedClass => {
        Object.getOwnPropertyNames(extendedClass.prototype).forEach(name => {
            Object.defineProperty(
                baseClass.prototype,
                name,
                Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || Object.create(null)
            )
        })
    })
}
Copied to clipboard!

The way this function works is it expects a class that needs to be extended with other classes, and an array of classes where the extension should come from. It loops through each class and copies the properties and methods over to the base class.

This way, you will have the extended properties and methods available for you to use on your base class. You can call this function in the following way:

class Enemy {
    attack() { ... }
}

class Boss {
    ultimateAttack() { ... }
}

class Entity implements Enemy, Boss {
    spawn() { ... }
}

applyMixins(Entity, [Enemy, Boss])

const boss = new Entity()

boss.spawn()
boss.attack()
boss.ultimateAttack()
Copied to clipboard!

Call the function with the class that needs to be extended, and pass the classes as an array that you want to extend from. Now you are able to call both methods from both classes on the extended class.

Share on
  • twitter
  • facebook
JavaScript Course Dashboard

Tired of looking for tutorials?

You are not alone. Webtips has more than 400 tutorials which would take roughly 75 hours to read.

Check out our interactive course to master JavaScript in less time.

Learn More

Recommended

πŸŽ‰ Thank you for subscribing to our newsletter. x