Intermediate · 11 of 16 · 14 min read
Generic interfaces and classes
Putting the type parameter on the container rather than the function — the envelope pattern, binding a parameter at implementation time, and generic classes.
- Generics
A generic function keeps a relationship across one call. A generic interface or class keeps one across a whole shape — the envelope stays the same and the payload varies.
Generic interfaces
interface ApiResponse<T> {
status: number;
timestamp: Date;
data: T;
}
interface User { id: number; name: string }
const a: ApiResponse<User> = {
status: 200,
timestamp: new Date(0),
data: { id: 1, name: "Ana" },
};
const b: ApiResponse<string[]> = { status: 200, timestamp: new Date(0), data: ["x"] };
console.log(a.data.name, b.data.length); // "Ana" 1
Without the parameter you would need UserResponse, OrderResponse and so on — identical but for
one property, and all of them to update when the envelope gains a field.
A default makes the argument optional:
interface ApiResponse<T = unknown> {
status: number;
data: T;
}
const empty: ApiResponse = { status: 204, data: null }; // T is unknown
console.log(empty.status);
Defaults matter more for types than for functions: a type has no arguments to infer from, so without one the parameter must always be written.
Several parameters, and constraints
interface Paginated<T, Cursor = string> {
items: T[];
next: Cursor | null;
}
interface Store<T extends { id: number }> {
byId: Map<number, T>;
add(item: T): void;
}
const page: Paginated<string> = { items: ["a"], next: null };
// const bad: Store<{ name: string }> = …; // missing 'id'
console.log(page.items.length);
A constraint on an interface parameter does the same job as on a function: it is what the interface’s own members are allowed to assume.
Binding the parameter at implementation time
This is the shape the source material calls out, and the one that comes up in interviews:
interface Repository<T> {
getAll(): T[];
add(item: T): void;
}
class StringRepository implements Repository<string> {
private items: string[] = [];
getAll(): string[] { return this.items; }
add(item: string): void { this.items.push(item); }
}
const repo = new StringRepository();
repo.add("Hello");
repo.add("World");
console.log(repo.getAll()); // ["Hello", "World"]
Repository<T> is the contract; StringRepository fixes T to string and implements it
concretely. The class is not generic — it has chosen.
The alternative is to stay generic and let the consumer choose:
interface Repository<T> {
getAll(): T[];
add(item: T): void;
}
class InMemoryRepository<T> implements Repository<T> {
private items: T[] = [];
getAll(): T[] { return this.items; }
add(item: T): void { this.items.push(item); }
}
const users = new InMemoryRepository<{ id: number }>();
users.add({ id: 1 });
console.log(users.getAll()[0]?.id); // 1
Both are correct; they differ in who decides. A UserRepository implements Repository<User> is
usually what an application wants, because the concrete one also has room for findByEmail.
Generic classes
class KeyValuePair<K, V> {
constructor(
private key: K,
private value: V,
) {}
describe(): string {
return `${String(this.key)}=${String(this.value)}`;
}
get(): [K, V] { return [this.key, this.value]; }
}
const a = new KeyValuePair("id", 101); // <string, number>
const b = new KeyValuePair<number, string>(1, "Ana");
console.log(a.describe(), b.describe()); // "id=101" "1=Ana"
Constructor arguments are inferred exactly like function arguments, so the explicit form is only needed when there is nothing to infer from — or when you want something wider:
class Box<T> {
constructor(public value: T) {}
}
const inferred = new Box("x"); // Box<string>
const widened = new Box<string | null>("x"); // so it can hold null later
widened.value = null;
console.log(inferred.value, widened.value);
| Parameter on | Decided when | Typical use |
|---|---|---|
| a function | each call | a transformation |
| an interface | each use of the type | an envelope, a contract |
| a class | each new |
a container with state |
an implements clause |
at the class declaration | a concrete implementation of a contract |
Static members cannot use the parameter
A class parameter belongs to an instance, so a static member cannot see it:
class Box<T> {
constructor(public value: T) {}
// static empty: T; // Static members cannot reference class type parameters
static of<U>(value: U): Box<U> { // a generic static method works
return new Box(value);
}
}
console.log(Box.of("x").value); // "x"
The workaround is the one shown: give the static method its own parameter.
Generic methods inside a generic class
A method can introduce parameters of its own, independent of the class’s:
class Collection<T> {
constructor(private items: T[]) {}
map<U>(fn: (item: T) => U): Collection<U> {
return new Collection(this.items.map(fn));
}
first(): T | undefined { return this.items[0]; }
}
const names = new Collection(["Ana", "Beto"]);
const lengths = names.map((n) => n.length); // Collection<number>
console.log(lengths.first()); // 3
map<U> is the same signature Array.prototype.map has, and for the same reason: the result’s
element type is whatever the callback returns.
Common mistakes
A generic interface used with any
Mistake. ApiResponse<any> to avoid naming the payload.
Why it fails. The parameter existed to carry the type, and any throws it away — along with
everything downstream of response.data.
What to do instead. Name the payload type, or unknown plus a guard if it really is
unverified.
Making a class generic when one method needs the parameter
Mistake. class Formatter<T> where only format(value: T) uses it.
Why it fails. Every construction now has to decide T, for one method’s benefit.
What to do instead. Put the parameter on the method: format<T>(value: T).
Implementing a generic interface without fixing or forwarding the parameter
Mistake. class UserRepository implements Repository<T> with no T in scope.
Why it fails. T is not declared anywhere — the class has to either name a concrete type or
declare its own parameter.
What to do instead. implements Repository<User>, or class Repo<T> implements Repository<T>.
Check yourself
2 questions from the bank on what you just read. Answering here does not affect your quiz history.
What does a generic interface like ApiResponse<T> let you avoid?
A generic class binds its parameters when an instance is created, and they can be inferred.
What types does new KeyValuePair("id", 101) produce?
class KeyValuePair<K, V> {
constructor(public key: K, public value: V) {}
}Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.