TypeScript
/Intermediate
Generic Interfaces
Definition
Interfaces that use generic type variables to allow their structure to be reusable across different data types.
Explain Like I'm New
Imagine a standardized 'Shipping Box' interface. The box has a tracking number, a weight, and 'contents'. But the 'contents' could be literally anything. A Generic Interface lets you define the box structure once, and later specify exactly what is inside: `ShippingBox<Books>` or `ShippingBox<Shoes>`.
Real World Example
Typing a standardized API response. `interface ApiResponse<DataShape> { status: number; data: DataShape; error?: string; }`
Common Use Cases
- •Standardizing API responses
- •Paginated data structures
- •Reusable UI component props
Interactive Example
// The core wrapper is always the same, only 'data' changes interface ApiResponse<T> { status: number; success: boolean; data: T; // The type passed in goes here } interface User { name: string; } interface Post { title: string; } // Creating a specific response for Users const userRes: ApiResponse<User> = { status: 200, success: true, data: { name: "Alice" } }; // Creating a specific response for an Array of Posts const postRes: ApiResponse<Post[]> = { status: 200, success: true, data: [{ title: "TS is great" }, { title: "I love Generics" }] };
Interview Questions
basic
- How do you pass a type into a Generic Interface?
intermediate
- Can a Generic Interface have a default type?
advanced
- How do you use a Generic Interface with an Array type?