MediumJavaScriptTypeScript

Generic Stack<T>

TypeScriptTypesPatterns

Generics allow a class to work with different types while maintaining full type safety. Without generics, a Stack would accept and return any:

// Without generics — loses type information:
class Stack {
  push(item: any): void { ... }
  pop(): any { ... }         // caller doesn't know what they get back
}

// With generics — full type safety:
class Stack<T> {
  push(item: T): void { ... }
  pop(): T | undefined { ... } // TypeScript knows the exact type
}

const stack = new Stack<number>();
stack.push(42);           // ✅
stack.push('hello');      // ❌ TypeScript error
const top = stack.pop();  // TypeScript: number | undefined ✅

Implement Stack<T>

MethodReturn typeBehavior
push(item)numberAdds item, returns new size
pop()`T \undefined`Removes and returns top
peek()`T \undefined`Returns top without removing
size()numberCurrent item count
isEmpty()booleanTrue when size is 0
toArray()T[]Copy: bottom to top

Sample tests

Test #1pop from empty stack returns null (undefined mapped to null)
Input: [[["pop"]]]
Output: [null]
Test #2toArray returns bottom-to-top copy
Input: [[["push",10],["push",20],["toArray"]]]
Output: [1,2,[10,20]]
Test #3push twice then check size
Input: [[["push",1],["push",2],["size"]]]
Output: [1,2,2]
Test #4new stack is empty
Input: [[["isEmpty"]]]
Output: [true]
Test #5peek returns top without removing
Input: [[["push","a"],["push","b"],["peek"]]]
Output: [1,2,"b"]
Test #6pop removes the top
Input: [[["push",1],["push",2],["push",3],["pop"],["size"]]]
Output: [1,2,3,3,2]