TypeScript · Lesson 25 of 42
Generic interfaces, type aliases and classes
Parameterise interfaces, type aliases and classes with type parameters, set default types, and see how Array<T> and Promise<T> are built the same way.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will create types that are templates: a container, a response wrapper, a data structure, each working for any content type while staying fully checked. This extends the idea of generic functions to the types you declare.
Generic interfaces and type aliases
An interface or a type alias can take type parameters in angle brackets after its name:
interface Box<T> {
value: T;
}
const numberBox: Box<number> = { value: 42 };
const stringBox: Box<string> = { value: "hello" };
console.log(numberBox.value + 1, stringBox.value.toUpperCase());43 HELLOBox<T> is a template, and Box<number> fills it in. When you use a generic type, you must give the type argument, and the compiler checks the value against it:
interface Box<T> {
value: T;
}
const wrong: Box<number> = { value: "hello" };example.ts(5,30): error TS2322: Type 'string' is not assignable to type 'number'.Type aliases work the same way. A very common real-world use is a wrapper for API responses:
type ApiResponse<T> =
| { status: "ok"; data: T }
| { status: "error"; message: string };
type User = { id: number; name: string };
function show(response: ApiResponse<User>): string {
if (response.status === "ok") {
return `Hello, ${response.data.name}`;
}
return `Failed: ${response.message}`;
}
console.log(show({ status: "ok", data: { id: 1, name: "Asha" } }));
console.log(show({ status: "error", message: "not found" }));Hello, Asha
Failed: not foundOne definition, ApiResponse<T>, describes the response for users, products or anything else. It is also a discriminated union, so narrowing on status works as in the earlier lesson.
Several parameters and default types
A generic type may have more than one parameter. You can also give a parameter a default, used when the caller does not supply one:
interface Pair<A, B = A> {
first: A;
second: B;
}
const names: Pair<string> = { first: "Asha", second: "Ben" };
const mixed: Pair<string, number> = { first: "age", second: 30 };
console.log(names, mixed);{ first: 'Asha', second: 'Ben' } { first: 'age', second: 30 }In Pair<string>, B defaults to A, so both are strings. Defaults keep the common case short while allowing flexibility.
Generic classes
A class can take type parameters too. The classic example is a data structure that holds items of one type:
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
get size(): number {
return this.items.length;
}
}
const numbers = new Stack<number>();
numbers.push(1);
numbers.push(2);
console.log(numbers.pop(), numbers.size);2 1Each Stack is created for one type. Pushing the wrong kind of thing is an error:
class Stack<T> {
private items: T[] = [];
push(item: T): void {
this.items.push(item);
}
}
const numbers = new Stack<number>();
numbers.push("three");example.ts(10,14): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.Classes are covered in detail in a later section. For now, notice that the same type parameter T appears throughout the class, tying its methods together.
Constraints on generic types
Type parameters on interfaces and classes can also have constraints with extends, exactly as on functions:
interface HasName {
name: string;
}
class Registry<T extends HasName> {
private items = new Map<string, T>();
add(item: T): void {
this.items.set(item.name, item);
}
get(name: string): T | undefined {
return this.items.get(name);
}
}
const registry = new Registry<{ name: string; price: number }>();
registry.add({ name: "pen", price: 2 });
console.log(registry.get("pen")?.price);2You have used generic types all along
Several types you already know are generic:
Array<T>is the long form ofT[]. Sostring[]isArray<string>.Promise<T>describes a value that arrives later (the next sections cover it).Map<K, V>andSet<T>are the built-in collections, as theRegistryabove used.Record<K, V>describes an object with keysKand valuesV.
Seeing them as generic types explains why they have angle brackets and why the compiler knows what you get out of them.
Common mistakes
Forgetting the type argument. Box alone is an error when the type parameter has no default. Write Box<number>.
Using generics for a single concrete case. If a type will only ever hold numbers, do not parameterise it.
Confusing the type parameter with a value. T exists only for the compiler. You cannot write new T() or typeof T in the running code.
Giving too many type parameters. Each one makes the type harder to read. Two or three is plenty for most designs.
Exercise
Write interface Result<T, E = string> as a discriminated union with success and failure, and use it for a function that parses an integer. Write class Queue<T> with enqueue, dequeue and a size getter. Create a Queue<string> and a Queue<number>, and try mixing the types to read the error.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.