Sub topic 2
TypeScript Generics: Generic Classes
Assume you know basic TypeScript types, interfaces, type aliases, functions, unions, and class syntax. This chapter focuses on how generic classes keep one precise type across their methods.
Generic Classes
A generic class receives a type parameter when you create an instance. The class then uses that type consistently.
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
}
const numbers = new Stack<number>();
numbers.push(10);
const value = numbers.pop(); // number | undefinedThe numbers stack accepts only numbers. A Stack<string> would accept only strings. The same class works with many types without replacing type information with any.
Constraining Type Parameters with extends
Sometimes a class should accept only types with a required shape. An extends constraint limits valid type arguments.
class Repository<T extends { id: string }> {
private records: T[] = [];
add(record: T): void {
this.records.push(record);
}
find(id: string): T | undefined {
return this.records.find(record => record.id === id);
}
}
type User = {
id: string;
name: string;
};
const users = new Repository<User>();
users.add({ id: "u1", name: "Ada" });
// Repository<number>; // Error: number has no string idThe constraint also lets the class safely use record.id. Without the constraint, TypeScript could not guarantee that every T has an id.
keyof and Indexed Access Types
keyof T produces a union of the property names of T. An indexed access type, written T[K], produces the type stored at a selected property.
function getProperty<T, K extends keyof T>(object: T, key: K): T[K] {
return object[key];
}
const user = { id: "u1", name: "Ada" };
const name = getProperty(user, "name"); // stringThe constraint on K prevents invalid property names while preserving the exact result type.
> callout note > Use keyof when a key must come from an object. Use T[K] when the return type should match the selected property.
Default Type Parameters
A default type parameter supplies a type when the caller omits one.
interface ApiResponse<T = unknown> {
data: T;
status: number;
}
const response: ApiResponse = {
data: "unverified",
status: 200
};
const users: ApiResponse<User[]> = {
data: [{ id: "u1", name: "Ada" }],
status: 200
};unknown is safer than any because code must check the value before using it.
Exercise
Why does Repository<User> accept User, but Repository<number> fail?
Show answer
The extends { id: string } constraint requires every type argument to contain a string id property.