Generic class in TypeScript
A generic class in TypeScript is a class that works with different data types, while still keeping strong type safety.
Think of it as one reusable class that can adapt to many types, without losing correctness.
Why generic classes are needed
Without generics, type safety is lost:
class Box {
value: any;
constructor(value: any) {
this.value = value;
}
}
const box = new Box(123);
box.value.toUpperCase(); // runtime error
TypeScript cannot protect you here.
Basic idea of a generic class
A generic class uses a type parameter, usually named T, to represent a type that will be decided later.
Conceptually:
The class does not know the type yet
The type is chosen when creating an instance
The same type is used everywhere inside the class
Generic class example (conceptual)
class Box {
value: T;
constructor(value: T) {
this.value = value;
}
}
When you create an object:
T becomes number
or T becomes string
or any other type
The class logic stays the same.
Type inference (most common usage)
TypeScript usually figures out the type automatically:
const box = new Box("hello");
Here:
T is treated as string
box.value is string
string methods are allowed
number methods are rejected
Generic class with methods
Generic types can be used in properties and methods.
class Storage {
private items: T[] = [];
add(item: T) {
this.items.push(item);
}
getAll() {
return this.items;
}
}
This ensures:
Only one type is stored
No mixing of incompatible values
Multiple generic types
A class can work with more than one type at the same time.
Conceptually:
One type for the key
One type for the value
class KeyValuePair {
key: K;
value: V;
constructor(key: K, value: V) {
this.key = key;
this.value = value;
}
}
This is common in maps, caches, and dictionaries.
Generic constraints (restricting types)
Sometimes you want to allow only certain kinds of types.
Example rule:
The type must have a length property
class LengthLogger {
log(value: T) {
console.log(value.length);
}
}
Allowed:
strings
arrays
Not allowed:
numbers
booleans
Generic class with interfaces
Generic classes are often used with interfaces to build reusable systems like repositories or services.
Concept:
Interface defines behavior
Generic class provides implementation
Type stays consistent
This pattern is extremely common in backend and frontend applications.
Important rule about static and generics
Static members:
Belong to the class
Do NOT know what the generic type is
So:
Instance methods can use T
Static methods cannot use T
This is a common beginner mistake.
When to use a generic class
Use a generic class when:
The same logic works for many types
You want strong type safety
Types must stay consistent across methods
Avoid generic classes when:
Types are unrelated
A simple specific class is enough
A union type would be simpler