Implementing Generic Interfaces
What you'll learn: How to make your classes implement generic interfaces by providing concrete or generic type arguments.
The Core Idea
When a class implements a generic interface, you must decide which type(s) to fill in for the interface's type parameters. You have two choices:
- Provide concrete types — lock the class to specific types like
stringornumber - Make the class generic too — pass the decision up to whoever creates instances of your class
Think of it like a contract template: the interface says "you must have these properties and methods, but I don't know the exact types yet." When you implement it, you either fill in those blanks yourself or pass the template along for others to complete.
Concrete Type Arguments
interface Container<T> {
value: T;
getValue(): T;
}
// Lock it to numbers
class NumberBox implements Container<number> {
constructor(public value: number) {}
getValue(): number {
return this.value;
}
}
const numBox = new NumberBox(42);
Here, NumberBox commits to T being number.
Generic Type Arguments
// Pass the generic along
class GenericBox<T> implements Container<T> {
constructor(public value: T) {}
getValue(): T {
return this.value;
}
}
const strBox = new GenericBox<string>("hello");
const boolBox = new GenericBox<boolean>(true);
Now GenericBox itself is generic — users decide the type when creating instances.
Key Takeaway: When implementing a generic interface, you either satisfy its type parameters with concrete types (fixing them forever) or make your class generic too (deferring the choice to your users).