Interview Q&A / Machine Learning

BeginnerQuick answer1 min readUpdated 3 Oct 2026

How do you write a generic class in TypeScript, for example a Stack?

SHORT ANSWER

Put the type parameter after the class name, like class Stack<T>, and use T in fields and method signatures. Each instance fixes T when created, so new Stack<number>() only accepts and returns numbers.

Explain it simply

A stack of plates: it does not care whether the plates are steel or ceramic, but one stack should hold one kind. A generic class captures that. The class logic (push, pop) is written once, and each instance decides what it holds.

The compiler then stops you from pushing a string onto a stack of numbers, and pop() returns the right type without a cast.

Example

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

push(item: T): void { this.items.push(item); } pop(): T | undefined { return this.items.pop(); } get size(): number { return this.items.length; } }

const nums = new Stack<number>(); nums.push(10); nums.push(20); // nums.push("x"); // Error: string is not assignable to number console.log(nums.pop()); // 20, typed number | undefined

const names = new Stack<string>(); // separate instance, separate T

What to say in the interview

A generic class declares its type parameter after the name and uses it in properties and methods. T is chosen per instance, so one Stack implementation serves numbers, strings or objects with full type checking. Note that static members cannot use the class's T.

Common mistakes

  • Using T inside a static method; static members belong to the class, not an instance.

#generics#classes

Related questions

Practise more Machine Learning questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Machine Learning quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.