Skip to main content

Mixins & Decorators in TypeScript (Live Playground)

In this tutorial, we will explore mixins and decorators in TypeScript, which are powerful techniques in advanced object-oriented programming (OOP).

Mixins

Mixins are a mechanism that allows you to compose multiple classes into a single class. Mixins can be used to implement multiple inheritance in TypeScript.

TypeScript
type Constructor<T = {}> = new (...args: any[]) => T;

function FlyMixin<TBase extends Constructor>(Base: TBase) {
return class extends Base {
fly(): void {
console.log('I can fly!');
}
};
}

class Animal {
constructor(public name: string) {}
}

const FlyingAnimal = FlyMixin(Animal);

class Bird extends FlyingAnimal {
constructor(name: string) {
super(name);
}
}

const bird = new Bird('Eagle');
bird.fly(); // I can fly!
Live Playground, Try it Yourself

Decorators

Decorators are a special kind of declaration that can be attached to classes, methods, properties, and parameters. They can be used to modify or extend the behavior of the target element.

Class Decorators

A class decorator is a function that takes a class constructor as its only argument and can return a new constructor or modify the input class.

TypeScript
function AnimalDecorator<T extends { new (...args: any[]): {} }>(constructor: T) {
return class extends constructor {
name = 'Decorated ' + this.name;
};
}

@AnimalDecorator
class Animal {
constructor(public name: string) {}
}

const animal = new Animal('Dog');
console.log(animal.name); // Decorated Dog

Method Decorators

A method decorator is a function that takes the target object, property key, and property descriptor as its arguments. It can be used to modify the behavior of the method.

TypeScript
function LogDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;

descriptor.value = function (...args: any[]) {
console.log(`Calling ${propertyKey} with args: ${JSON.stringify(args)}`);
return originalMethod.apply(this, args);
};
}

class Calculator {
@LogDecorator
sum(a: number, b: number): number {
return a + b;
}
}

const calculator = new Calculator();
calculator.sum(1, 2); // Calling sum with args: [1,2]

Conclusion

In this tutorial, we have explored mixins and decorators in TypeScript, which are powerful techniques in advanced object-oriented programming (OOP). As you continue learning TypeScript, make sure to practice using mixins, decorators, and other OOP techniques to create more flexible, reusable, and maintainable code in your applications.