Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you provide an example of a generic class in TypeScript


Can you provide an example of a generic class in TypeScript


Sure, here's an example of a generic class in TypeScript:

typescript
class Stack<T> {
  private items: T[] = [];

  push(item: T): void {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }

  peek(): T | undefined {
    return this.items[this.items.length - 1];
  }

  isEmpty(): boolean {
    return this.items.length === 0;
  }

  size(): number {
    return this.items.length;
  }
}

// Using the generic Stack class
const numberStack = new Stack<number>();
numberStack.push(1);
numberStack.push(2);
numberStack.push(3);

console.log(numberStack.pop()); // Output: 3
console.log(numberStack.peek()); // Output: 2
console.log(numberStack.size()); // Output: 2

const stringStack = new Stack<string>();
stringStack.push("hello");
stringStack.push("world");

console.log(stringStack.pop()); // Output: "world"
console.log(stringStack.peek()); // Output: "hello"
console.log(stringStack.size()); // Output: 1

In this example, we define a generic `Stack` class that can hold elements of any type `T`. The class has the following methods:

- `push(item: T)`: Adds an item of type `T` to the top of the stack.
- `pop(): T | undefined`: Removes and returns the top item from the stack, or `undefined` if the stack is empty.
- `peek(): T | undefined`: Returns the top item from the stack without removing it, or `undefined` if the stack is empty.
- `isEmpty(): boolean`: Returns `true` if the stack is empty, `false` otherwise.
- `size(): number`: Returns the number of items in the stack.

We then create two instances of the `Stack` class, one for `number` and one for `string`, and demonstrate how to use the generic class with different types.

The key benefits of using a generic class in this example are:

1. Type safety: The generic type parameter `T` ensures that the stack can only hold elements of the same type, preventing type-related errors.
2. Reusability: The `Stack` class can be used with any type, making it more reusable and flexible.
3. Maintainability: By using generics, the code becomes more readable and easier to understand, as the type information is explicit.

This is just one example of how you can use generics to create more flexible and type-safe classes in TypeScript. Generics can be used in a variety of contexts, such as functions, interfaces, and type aliases, to improve the overall quality and robustness of your TypeScript code.