What if one class could safely handle any type of data without rewriting code?
Why Generic class syntax in Typescript? - Purpose & Use Cases
Imagine you want to create a class that can store different types of data, like numbers, strings, or even custom objects. Without generics, you'd have to write a new class for each type or use a very loose type like any, which can cause mistakes.
Writing separate classes for each data type is slow and repetitive. Using any removes type safety, so you might accidentally mix types and get errors only when running your code, making debugging hard and frustrating.
Generic class syntax lets you write one flexible class that works with any data type while keeping type safety. You tell the class what type to use when creating it, so TypeScript helps catch mistakes early and saves you from writing repetitive code.
class NumberBox { value: number; constructor(value: number) { this.value = value; } } class StringBox { value: string; constructor(value: string) { this.value = value; } }
class Box<T> {
value: T;
constructor(value: T) {
this.value = value;
}
}You can create reusable, type-safe classes that adapt to any data type, making your code cleaner and safer.
Think of a storage box that can hold toys, books, or clothes. Instead of making a new box for each, you make one adjustable box that fits anything you want to store.
Writing separate classes for each type is slow and error-prone.
Generic classes let you write one flexible, reusable class.
This keeps your code safe and easier to maintain.
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
