Generic Classes in TypeScript

TypeScript Generics: How to Use Generic Types in TypeScript

In TypeScript, you can create generic classes that allow you to define a class with placeholders for its types. This means that you can write code that is reusable and works with different types of data. In this lesson, we will go over how to create generic classes in TypeScript with a code example.

Creating a Generic Class

To create a generic class in TypeScript, you use angle brackets <> to define the type placeholders. Here’s an example:

class MyGenericClass<T> {
  private data: T[];

  constructor() {
    this.data = [];
  }

  add(item: T) {
    this.data.push(item);
  }

  remove(item: T) {
    const index = this.data.indexOf(item);
    if (index > -1) {
      this.data.splice(index, 1);
    }
  }

  getAll(): T[] {
    return this.data;
  }
}

In this example, we define a generic class called MyGenericClass with a type placeholder T. The class has an array called data of type T[] to store the data. The add, remove, and getAll methods operate on this array.

Using a Generic Class

To use a generic class, you specify the type for the type placeholder T when you create an instance of the class. Here’s an example:

const stringList = new MyGenericClass<string>();
stringList.add('hello');
stringList.add('world');
stringList.remove('world');
console.log(stringList.getAll()); // ['hello']

const numberList = new MyGenericClass<number>();
numberList.add(1);
numberList.add(2);
numberList.remove(2);
console.log(numberList.getAll()); // [1]

In this example, we create two instances of the MyGenericClass class. The first instance is for a list of strings and the second instance is for a list of numbers. We add and remove items from each list and then print out the resulting list using the getAll method.

Conclusion

In conclusion, generic classes in TypeScript allow you to create classes that work with different types of data. By using a type placeholder, you can create classes that are more flexible and reusable. You can use generic classes to create data structures, algorithms, and more.