Photo by Pawel Czerwinski on Unsplash
Generic types are very useful when we want to create a reusable type/interface that can be changed based on the type parameter we sent.
Example:
In this case, we play a role as a frontend dev and we need to create an interface for API that has the following response:
{
"success": true,
"data": {
"user_id": "123asd",
"status": "online"
}
}
For the starter, we might use this interface for the above API response:
// You can also use type instead of interface
interface APIResponse {
success: boolean;
data: {
"user_id": string,
"status": string
};
}
But... the above interface only works for one API response. What happens if we need to create an interface for another API response? For example, another API has the following response:
{
"success": true,
"data": {
"category_id": "cat123",
"is_active": true
}
}
Instead of rewriting the interface, we could create a dynamic type that accepts type parameters and set the data type dynamically.
Here is our final result:
// This the Generic Type that we currently talk about
interface APIResponse<T> {
success: boolean;
data: T;
}
interface User {
"user_id": string,
"status": string
}
interface Category {
"category_id": string,
"is_active": boolean
}
// Example usage
const res: APIResponse<User> = userApi.res;
const res: APIRes<Category> = userApi.res;