Understanding Mixins in TypeScript: Concept and Examples
What Are Mixins in TypeScript? Mixins in TypeScript provide a way to reuse code across multiple classes without using traditional inheritance. A mixin is a class or function containing properties or methods that can be added to other classes, offering flexible code sharing beyond single inheritance. Avoid duplication: Share common methods across different classes Flexible composition: Combine features from multiple sources Workaround TypeScript limitations: TypeScript (and JavaScript) only support single class inheritance Mixins are implemented by writing functions that take a base class and extend it with new functionality. TypeScript supports this using interfaces and higher-order functions. // A generic constructor type type Constructor = new (...args: any[]) => T; // Mixin function function Flyer(Base: TBase) { return class extends Base { fly() { console.log('Flying!'); } }; } // Using the mixin class Animal { move() { console.log('Moving!'); } } // Apply the Flyer mixin to Animal class Bird extends Flyer(Animal) {} const sparrow = new Bird(); sparrow.move(); // Output: Moving! sparrow.fly(); // Output: Flying! Mixins allow combining behaviors from multiple sources, solving the single inheritance issue. Use interface to declare what mixin methods will be available. Always use constructor signatures for mixin functions. function Swimmer(Base: TBase) { return class extends Base { swim() { console.log('Swimming!'); } }; } class Fish extends Swimmer(Flyer(Animal)) {} const goldfish = new Fish(); goldfish.move(); // Output: Moving! goldfish.fly(); // Output: Flying! goldfish.swim(); // Output: Swimming! Mixins are a powerful pattern in TypeScript for reusing functionality without complex inheritance chains. They help organize code more clearly and encourage composition over inheritance.
