create a generic interface in typescript

To create a generic interface in TypeScript, we can use the interface keyword followed by the name of the interface and a set of angled brackets containing one or more type parameters. For example, we can create a Stack interface with a generic T parameter representing the type of elements in the stack:

index.ts
interface Stack<T> {
  push(item: T): void;
  pop(): T | undefined;
  readonly size: number;
}
95 chars
6 lines

In this example, the Stack interface specifies three methods: push to add an item of type T to the stack, pop to remove and return the top item from the stack, and size to return the number of items in the stack. The T type parameter can be replaced with any type when using this interface.

We can also use generic types in combination with classes. For example, we can create a LinkedList class with a generic T parameter representing the type of data stored in the list nodes:

index.ts
class LinkedListNode<T> {
  data: T;
  next: LinkedListNode<T> | null;
  constructor(data: T, next: LinkedListNode<T> | null = null) {
    this.data = data;
    this.next = next;
  }
}

class LinkedList<T> {
  head: LinkedListNode<T> | null = null;
  tail: LinkedListNode<T> | null = null;
  append(data: T): void {
    const node = new LinkedListNode(data);
    if (!this.head) {
      this.head = node;
      this.tail = node;
      return;
    }
    this.tail!.next = node;
    this.tail = node;
  }
}
505 chars
24 lines

In this example, the LinkedListNode class represents a node in the linked list with a data property of type T and a next property pointing to the next node in the list. The LinkedList class then uses this LinkedListNode class to construct a linked list data structure with append method to add new nodes to the end of the list.

Using generic types and interfaces can make our code more reusable and flexible, allowing us to write functions and classes that can work with different types of data.

gistlibby LogSnag