How to implement a stack in TypeScript

1 Answer

0 votes
class Stack<T> {
    private items: T[] = [];

    // Push an element onto the stack
    push(element: T): number {
        return this.items.push(element);
    }

    // Pop an element from the stack
    pop(): T | string {
        if (this.isEmpty()) {
            return "Stack is empty";
        }
        return this.items.pop() as T;
    }

    // Peek at the top element
    peek(): T | string {
        if (this.isEmpty()) {
            return "Stack is empty";
        }
        return this.items[this.items.length - 1];
    }

    // Check if the stack is empty
    isEmpty(): boolean {
        return this.items.length === 0;
    }

    // Get the size of the stack
    size(): number {
        return this.items.length;
    }

    // Print all elements
    print(): void {
        for (const item of this.items) {
            console.log(item);
        }
    }

    // Clear the stack
    clear(): void {
        this.items = [];
    }

    // Optional: expose items safely (read-only)
    getItems(): T[] {
        return [...this.items];
    }
}


const stack = new Stack<number>();

stack.push(12);
stack.push(17);
stack.push(18);
stack.push(19);
stack.push(20);
stack.push(21);

console.log(stack.pop());        // 21
console.log(stack.getItems());   // [12, 17, 18, 19, 20]

console.log(stack.peek());       // 20
console.log("size: " + stack.size());
console.log(stack.isEmpty());    // false

stack.pop();                     // removes 20
stack.print();                   // prints 12, 17, 18, 19

stack.clear();
console.log(stack.getItems());   // []



/*
run:

21 
[12, 17, 18, 19, 20] 
20 
"size: 5" 
false 
12 
17 
18 
19 
[] 

*/

 



answered Aug 15, 2025 by avibootz
...