ProgramGuru

Generic Classes

Understand Generic Classes

A generic class stores and operates on values of a selected type, such as a typed stack.

What you will learn: the purpose of generic classes, the rules TypeScript checks, and what its JavaScript behavior looks like in a runnable example.

What you’ll learn

  • Explain how generic classes works and where its type rules apply.
  • Predict the exact output of the generic classes example.
  • Diagnose a common issue: Do not expect new Box<number>(5) to perform automatic runtime rejection when a JavaScript caller later passes a string.

Build the mental model

The parameter T links a class’s fields, method inputs, and method outputs. Instances can be created for different types, but the emitted JavaScript class itself is not cloned per type argument.

Key distinction: TypeScript checks the declared types during development; emitted JavaScript carries out the value-level operation at runtime. A type declaration alone never validates untrusted runtime input.

See the relationship

Read this illustration from the first labeled part to the last. Compare it with the example and identify which parts are type checks and which parts run in JavaScript.

Generic Classes: explained visuallyBox<number> → set(12) → get(): numberBox<number>set(12)get(): numberFollow the values through the operation
Generic Classes: Box<number> → set(12) → get(): number.

Run the complete TypeScript example

This self-contained example uses fixed values, so it runs without reading input or depending on an external service. Paste it into the TypeScript Playground or save it as main.ts.

TypeScript program

class Box<T> {
  constructor(private value: T) {}
  get(): T { return this.value; }
  set(value: T): void { this.value = value; }
}
const box = new Box<number>(5);
box.set(12);
console.log(box.get() * 2);
const textBox = new Box("ready");
console.log(textBox.get().toUpperCase());

Verified output

24
READY

Run locally: npx tsc --strict --target es2022 --module commonjs main.ts, then node main.js. For projects with a tsconfig.json, build using that configuration instead.

Trace every important step

box is configured for number, so set(12) is accepted and get returns 12; doubling gives 24. textBox infers string from ready and returns READY after uppercasing.

Check each step: identify the input values, follow the JavaScript operation in execution order, and match the final expression with the exact output shown. An annotation can reject invalid source before execution, but does not change the value printed.

Avoid these common mistakes

Do not expect new Box<number>(5) to perform automatic runtime rejection when a JavaScript caller later passes a string.

How to debug: reproduce the issue in a minimal example. For compiler errors, inspect the inferred and declared types; for a runtime surprise, log the actual values and follow their references or branches.

Practice and experiment

Create a Store<T> that maintains a list of values and returns the last value or undefined.

Practice routine: predict the result on paper, edit one part of the code, compile under --strict, run the JavaScript, and explain whether TypeScript caught an error or JavaScript simply behaved differently.

Check your understanding

What is the benefit of Box<T> over Box<any>?
Choose one answer. You can try again.

Answer and explanation

Its get and set methods preserve the selected value type.

A generic class stores and operates on values of a selected type, such as a typed stack.

Review the key idea

Generic Classes: A generic class stores and operates on values of a selected type, such as a typed stack.

box is configured for number, so set(12) is accepted and get returns 12; doubling gives 24. textBox infers string from ready and returns READY after uppercasing.

Before continuing, explain one valid use case, one common pitfall, and the separation between compile-time checking and runtime behavior for this feature.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Default Generic Type Parameters →