class<T> Generic Classes
Last updated: 2026-10-22
class<T> Generic Classes
A generic class (class Stack<T>) binds the class structure to the stored data type: a Stack<number> instance only passes numbers in and out. Fields, method parameters and returns can all reference T — the whole state stays type-safe.
| Group | Generics |
|---|---|
| Kind | Syntax |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
class Stack<T> {
private items: T[] = [];
push(item: T): void { this.items.push(item); }
pop(): T | undefined { return this.items.pop(); }
size(): number { return this.items.length; }
}
const numStack = new Stack<number>();
⚙️ Parameters
| <T> | Class-level type parameter: fixed by new Stack<number>() and shared across the whole class |
|---|---|
| pop(): T | undefined | Return referencing T: popping an empty stack yields undefined, expressed honestly in the type |
Returns:Method returns are fixed by the instance's T: Stack<number>'s pop() is number | undefined.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
2 1
build
(Runtime output after transpilation; numStack.push("1") is a compile error — this instance's T is locked to number)
💡 Notes
ℹ️ Info T is one variable across the class: what you push is what you pop — the essential difference from an any-based container.
💡 Tip Static members cannot reference the class's T: statics are class-level, not per-instance; give static methods their own type parameters if needed.
⚠️ Note Type parameters apply on the instance side: Stack<number> and Stack<string> are incompatible types — assigning between them errors.
🏷️ Related Generics
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q Can I write new Stack() without <number>?
A Yes, when constructor arguments allow inference (new Stack([1, 2]) → Stack<number>); an empty constructor yields Stack<unknown>, so prefer writing it explicitly there.
Q How do you extend a generic class?
A Either fix T: class NumberStack extends Stack<number>; or carry your own: class Box<T> extends Stack<T> — the child's parameter must satisfy the parent's.
Q Do generic classes and interfaces work together?
A Extremely common: interface Repo<T> is the contract, class MemoryRepo<T> implements Repo<T> the implementation — both stay generic and the business layer gets precise types.