JS Built-ins
TypeScriptintermediate

Interface β€” Implement a Stack

πŸ“– Usage Example
function createStack<T>() {
  const items: T[] = []
  return {
    push: (x: T) => items.push(x),
    pop: () => items.pop(),
  }
}

Closures can implement interfaces without classes β€” returning an object with typed method signatures.

Interfaces as Contracts: Stack

Challenge: Implement createStack<T>() returning an object satisfying the Stack<T> interface.

const s = createStack<number>()
s.push(1); s.push(2)
s.pop()   // β†’ 2
s.peek()  // β†’ 1
s.size    // β†’ 1
πŸ’‘ Hints (1)
  • β€’ Use a getter for size so it reflects the current array length.