Welcome back! I am Mihir, and in this lesson we will learn generic interfaces in TypeScript.
A generic interface lets an interface work with different data types.
Basic Generic Interface
interface Box<T> {
value: T;
}
const stringBox: Box<string> = {
value: "Mihir",
};
const numberBox: Box<number> = {
value: 100,
};T changes based on how you use the interface.
API Response Example
interface ApiResponse<T> {
success: boolean;
data: T;
}
type User = {
id: number;
name: string;
};
const response: ApiResponse<User> = {
success: true,
data: {
id: 1,
name: "Mihir",
},
};The response wrapper is reusable for any data shape.
Generic Interface with Arrays
interface ListResponse<T> {
items: T[];
total: number;
}
const users: ListResponse<User> = {
items: [{ id: 1, name: "Mihir" }],
total: 1,
};This pattern is common for paginated APIs.
Generic Interface with Methods
interface Repository<T> {
findById(id: number): T | undefined;
save(item: T): void;
}Usage:
class UserRepository implements Repository<User> {
private users: User[] = [];
findById(id: number): User | undefined {
return this.users.find((user) => user.id === id);
}
save(user: User): void {
this.users.push(user);
}
}Multiple Generic Parameters
interface KeyValuePair<K, V> {
key: K;
value: V;
}
const setting: KeyValuePair<string, boolean> = {
key: "darkMode",
value: true,
};Use multiple parameters when more than one type can vary.
Default Generic Type
interface Result<T = string> {
value: T;
}
const defaultResult: Result = {
value: "Success",
};If no type is provided, T becomes string.
Quick Recap
- Generic interfaces make object shapes reusable.
- They are great for API responses and repositories.
- Generic methods can use the interface type parameter.
- Multiple generic parameters are allowed.
- Default generic types can make APIs easier to use.
Next up, we will learn Generic Classes →.