Generic Classes

1. Welcome and Icebreaker:

  • If you could design a container to hold anything, what would you put in it?

2. Outline the Session:

  • We’ll learn how to create generic classes in TypeScript.
  • Learning Outcomes: Understand how to write classes that work with any type.
  • Let’s build flexible data structures!

3. Concept Explanation:

  • Generic Classes use type parameters to work with any type.
  • Use <T> after the class name to define a generic class.
  • Useful for data structures like stacks, queues, or collections.
  • Syntax:
    class Box<T> {
      value: T;
      constructor(value: T) {
        this.value = value;
      }
    }
    

4. Live Coding Demonstration:

class Box<T> {
  value: T;
  constructor(value: T) {
    this.value = value;
  }
  getValue(): T {
    return this.value;
  }
}

const numberBox = new Box<number>(123);
console.log(numberBox.getValue()); // 123

const stringBox = new Box<string>("hello");
console.log(stringBox.getValue()); // "hello"

// Generic Stack class
class Stack<T> {
  private items: T[] = [];
  push(item: T) {
    this.items.push(item);
  }
  pop(): T | undefined {
    return this.items.pop();
  }
  peek(): T | undefined {
    return this.items[this.items.length - 1];
  }
}

const stack = new Stack<number>();
stack.push(1);
stack.push(2);
console.log(stack.pop()); // 2
console.log(stack.peek()); // 1

5. Tasks:

  • Short Exercise:
    1. Create a generic class Pair<T, U> that stores two values of possibly different types.
    2. Add methods to get each value.
    3. Create an instance of Pair with a string and a number, and print both values.
    4. Create a generic class Queue<T> with enqueue, dequeue, and size methods. Test it with strings.