Sub topic 4
Generic Interfaces and Type Aliases
Assume you know basic TypeScript types, interfaces, type aliases, functions, unions, and classes. This chapter focuses on putting type parameters on interfaces and aliases so one definition can describe many related types.
Why Generic Types Matter
A generic interface or type alias is a reusable type template. Its type parameter acts as a placeholder. Each use supplies a concrete type argument.
For example, a Box<T> describes a box containing one kind of value:
interface Box<T> {
value: T;
}
const numberBox: Box<number> = { value: 10 };
const textBox: Box<string> = { value: "hello" };The interface is written once, but Box<number> and Box<string> are different types. TypeScript checks the value inside each box:
// const invalid: Box<number> = { value: "ten" };
// Error: string is not assignable to numberThe type parameter preserves the relationship between the container and its contents. Using any would allow incorrect values and remove that protection.
Generic Interfaces
Generic interfaces work well when you want a named object shape that several parts of an application share.
interface ApiResponse<T> {
data: T;
status: number;
}
interface User {
id: number;
name: string;
}
const response: ApiResponse<User> = {
data: { id: 1, name: "Ada" },
status: 200,
};
console.log(response.data.name);Here, response.data is known to be a User, so TypeScript allows access to name. Another endpoint can use the same interface with a different argument:
const tagsResponse: ApiResponse<string[]> = {
data: ["typescript", "generics"],
status: 200,
};
console.log(tagsResponse.data.length);A generic interface can have more than one type parameter:
interface Pair<A, B> {
first: A;
second: B;
}
const entry: Pair<string, boolean> = {
first: "active",
second: true,
};The order of type arguments matters. Pair<string, boolean> is not the same as Pair<boolean, string>.
Generic Type Aliases
Type aliases can also accept type parameters. They are useful for tuples, unions, function types, and composed object types.
type Pair<A, B> = [A, B];
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
const coordinates: Pair<number, number> = [10, 20];
const success: Result<string> = {
ok: true,
value: "Saved",
};
const failure: Result<string> = {
ok: false,
error: "Network error",
};Both interfaces and type aliases can describe object shapes. Interfaces are often convenient for named, extendable object contracts. Type aliases are more flexible when the type is a union, tuple, or combination of other types.
| Need | Often a good choice | Column |
|---|---|---|
| A named object contract | `interface` | |
| A union or tuple | `type` | |
| A reusable type with parameters | Either | |
| Combining types with `&` or ` | ` | `type` |
Type Parameters Create Relationships
A type parameter is most useful when it appears in more than one place. In ApiResponse<T>, T connects the data property to the type chosen by the caller.
The type parameter can also appear in a function property:
interface Mapper<T, U> {
map(value: T): U;
}
const toLength: Mapper<string, number> = {
map(value) {
return value.length;
},
};
console.log(toLength.map("hello"));Mapper<string, number> requires a function that accepts a string and returns a number.
Exercise
Define a generic type alias named Result<T> that represents either { ok: true; value: T } or { ok: false; error: string }.
Show answer
type Result<T> = { ok: true; value: T } | { ok: false; error: string };