Skip to content
Justice Tech School

Generic Classes

Classes can take type parameters for containers.

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

Result

2

Exercise

Class generic.

class Box {}

Quiz Test

Why a generic Stack?

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