DEV Community

Cover image for A short note on TypeScript Mixins
Maciej Modzelewski
Maciej Modzelewski

Posted on • Updated on • Originally published at climbingdev.com

A short note on TypeScript Mixins

Hi there, so what are the TS Mixins?

In short, mixins are another way to extend your objects with common behaviours.

Let's assume that in a calendar app you can display list of users and list of meetings.
Regardless of the list type you can select an element of the list.

Let's look at the code to see how we could model this problem with mixins.

// We need a base type that can be extnended by any other type 
type Constructor<T = {}> = new (...args: any[]) => T;

// Here we create our mixin function. It can take any base type
// and extend it with one private propery and 3 methods.
function mixinSelectable<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    private _selected = false;

    select() {
      this._selected = true;
    }

    unselect() {
      this._selected = false;
    }

    get selected(): boolean {
      return this._selected;
    }
  };
}

class User {
  constructor(public firstName: string, public lastName: string) {}
}

class Meeting {
  constructor(public subject: string) {}
}

// This is how we create a new extended types 
const SelectableUser = mixinSelectable(User);
const SelectableMeeting = mixinSelectable(Meeting);

// Usage of new classes
const user = new SelectableUser('John', 'Locke');
user.select();
user.unselect();
user.selected;

const meeting = new SelectableMeeting('Learn Mixins');
meeting.select();
meeting.unselect();
meeting.selected;
Enter fullscreen mode Exit fullscreen mode

Mixins seem like a nice addition to OO features of TypeScript. They can help with managing a utility logic and nicely separate it from the business logic in our apps.

Hope you've learned something new today!

Happy coding! 😀

Top comments (0)