Tsallaka zuwa abun ciki
Justice Tech School

Generic Classes and Interfaces

Classes and interfaces can take type parameters, such as a typed Stack or a Result type.

Example
class Stack<T> {
  private items: T[] = [];
  push(x: T) { this.items.push(x); }
  pop(): T | undefined { return this.items.pop(); }
  get size() { return this.items.length; }
}
const s = new Stack<number>();
s.push(1); s.push(2);
console.log(s.pop(), s.size);

Result

2 1

Exercise

Declare a generic class.

class StackT> {}

Quiz Test

Why use a generic Stack?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.