Generic classes let you create flexible blueprints that work with many types, not just one. This helps you reuse code easily.
Generic class syntax in Typescript
class ClassName<T> { property: T; constructor(value: T) { this.property = value; } method(): T { return this.property; } }
The <T> after the class name means this class uses a generic type called T.
You can use T inside the class to represent any type given when creating an object.
Box holds one item of any type and returns it.class Box<T> { content: T; constructor(value: T) { this.content = value; } getContent(): T { return this.content; } }
const numberBox = new Box<number>(123); const stringBox = new Box<string>("hello");
T and U to hold two different types of values.class Pair<T, U> { first: T; second: U; constructor(first: T, second: U) { this.first = first; this.second = second; } }
This program creates a generic Storage class that can store items of any type. We make one storage for numbers and one for strings, add items, and print them.
class Storage<T> { private items: T[] = []; add(item: T): void { this.items.push(item); } getAll(): T[] { return this.items; } } const numberStorage = new Storage<number>(); numberStorage.add(10); numberStorage.add(20); console.log(numberStorage.getAll()); const stringStorage = new Storage<string>(); stringStorage.add("apple"); stringStorage.add("banana"); console.log(stringStorage.getAll());
You can use any name instead of T, but T is common and means 'Type'.
Generic classes help catch type errors early because TypeScript knows what type you expect.
You can have multiple generic types separated by commas, like <T, U>.
Generic classes let you write flexible, reusable code that works with many types.
Use <T> after the class name to declare a generic type.
Generic types keep your code safe and clear by knowing what type is used.
Practice
<T> mean in a TypeScript generic class declaration like class Box<T> {}?Solution
Step 1: Understand generic type parameter
The<T>after the class name declares a generic type parameter named T, which acts as a placeholder for any type.Step 2: Purpose of generic classes
This allows the class to work flexibly with any type specified when creating an instance, making the code reusable and type-safe.Final Answer:
It declares a placeholder type that can be replaced with any type when creating an instance. -> Option AQuick Check:
Generic <T> = placeholder type [OK]
- Thinking <T> fixes the type permanently
- Confusing generic syntax with inheritance
- Assuming <T> is a variable or value
Container with a type parameter T?Solution
Step 1: Recall generic class syntax
In TypeScript, generic classes use angle brackets<>to declare type parameters after the class name.Step 2: Match correct syntax
The correct syntax isclass Container<T> {}. Other options use parentheses, curly braces, or square brackets incorrectly.Final Answer:
class Container<T> {} -> Option DQuick Check:
Generic class uses <T> syntax [OK]
- Using parentheses instead of angle brackets
- Placing type parameter inside class body
- Using square brackets which are for arrays
class Box<T> {
content: T;
constructor(value: T) {
this.content = value;
}
getContent(): T {
return this.content;
}
}
const box = new Box<string>('hello');
console.log(box.getContent());Solution
Step 1: Understand class instantiation
The classBox<T>is instantiated withT = string, socontentis a string holding 'hello'.Step 2: Trace method call
The methodgetContent()returns the storedcontent, which is 'hello'. The console.log prints this string.Final Answer:
hello -> Option CQuick Check:
Generic class returns stored value 'hello' [OK]
- Expecting object print instead of string
- Confusing property with method output
- Thinking generic causes runtime error
class Pair<T, U> {
first: T;
second: U;
constructor(first: T, second: T) {
this.first = first;
this.second = second;
}
}Solution
Step 1: Compare constructor parameters with property types
The class declares two generic typesTandU, with propertiesfirst: Tandsecond: U.Step 2: Identify mismatch in constructor
The constructor incorrectly usessecond: Tinstead ofsecond: U, causing a type mismatch.Final Answer:
Constructor parameters should be (first: T, second: U) to match property types. -> Option AQuick Check:
Constructor params must match generic property types [OK]
- Using same type for both parameters ignoring generics
- Removing one generic parameter incorrectly
- Thinking constructor can't have parameters in generics
Dictionary<K, V> that stores key-value pairs. Which implementation correctly uses generics to store and retrieve values by key?class Dictionary<K, V> {
private items: Map<K, V> = new Map();
add(key: K, value: V): void {
this.items.set(key, value);
}
get(key: K): V | undefined {
return this.items.get(key);
}
}Solution
Step 1: Analyze Map usage with generics
The class usesMap<K, V>to store keys of type K and values of type V, which is correct.Step 2: Check methods for correct generic usage
Theaddmethod sets a key-value pair, andgetretrieves the value by key, both using the generic types properly.Final Answer:
This implementation correctly uses generics to store and retrieve values by key. -> Option BQuick Check:
Generic Map<K, V> with add/get methods = correct [OK]
- Swapping key and value types in Map declaration
- Expecting add to return a value unnecessarily
- Believing generics can't be used with built-in types
Ready to prove it?
Pass the test and this pattern moves unknown
