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.

GroupGenerics
KindSyntax
Strict modeNot 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 | undefinedReturn 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.
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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏