TypeScript Course
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

Loading Code Playground...

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?

Flash Cards

Question

Can it have a default type?

Click to reveal answer
Answer

Yes! Just like default function parameters, you can do `interface Box<T = string>`. If you use `Box` without specifying a type, it defaults to a box containing a string.