WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

TypeScript · Advanced · question 44 of 100

How can you create and use mixin classes in TypeScript?

📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

In TypeScript, mixins are a pattern that allows you to create reusable pieces of code and combine them into classes. A mixin is a function that accepts a class and returns a new class with additional or modified functionality.

Let’s look at an example of creating and using mixin classes in TypeScript.

Suppose we have two functionalities that we want to reuse in multiple classes: ‘Loggable‘ and ‘Serializable‘. Here’s how we can create mixin functions for these functionalities:

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

function Loggable<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    log() {
      console.log("Loggable mixin: ", this);
    }
  };
}

// Serializable mixin
function Serializable<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    serialize() {
      return JSON.stringify(this);
    }
  };
}

Now, let’s create a class ‘Person‘ that uses these mixins:

class Person {
  constructor(public name: string, public age: number) {}
}

// Apply both mixins to Person class
const LoggableSerializablePerson = Serializable(Loggable(Person));

// Create a new instance and use mixin methods
const person = new LoggableSerializablePerson("Alice", 30);
person.log();
console.log(person.serialize());

Here, we defined mixin functions ‘Loggable‘ and ‘Serializable‘ by extending the provided ‘Base‘ class and adding new methods. Then, we created a regular ‘Person‘ class and combined it with these mixins using the ‘Serializable(Loggable(Person))‘ syntax. This produces a new class that has all the functionalities of the ‘Person‘, ‘Loggable‘ and ‘Serializable‘ mixins.

When creating a new ‘LoggableSerializablePerson‘ instance, we can call both the ‘log‘ and ‘serialize‘ methods, as they have been mixed into the class.

In summary, creating and using mixin classes in TypeScript involves:

1. Define mixin functions that accept a base class and extend it with new functionality.

2. Apply mixins to a class by wrapping them around the class.

3. Create instances of the mixed class and use their mixed methods.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic TypeScript interview — then scores it.
📞 Practice TypeScript — free 15 min
📕 Buy this interview preparation book: 100 TypeScript questions & answers — PDF + EPUB for $5

All 100 TypeScript questions · All topics