AI Hints
Home›TypeScript Tutorial›Generic Types
TypeScript · Lesson 55 of 120

Generic Interfaces

Boxes of anything.

⏱ 2 min read▶ Video at 43:19🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Interfaces and type aliases can have type parameters too. A common example is an API response. The wrapper is always the same, but the data inside changes.

Generic Interfaces
From the video: Generic Interfaces
  • Generic interfaces
  • Same wrapper
  • Different data

A generic response

Api response of T has an ok flag, and data of type T. One response holds a list of bikes, another holds a single order. Run it.

app.tstypescript
interface ApiResponse<T> {
  ok: boolean;
  data: T;
}

type Bike = { model: string; price: number };

const bikes: ApiResponse<Bike[]> = { ok: true, data: [{ model: "Volt 7", price: 2199 }] };
const order: ApiResponse<{ id: number }> = { ok: true, data: { id: 1042 } };

console.log(bikes.data[0].model, "|", order.data.id);
Output
Volt 7 | 1042

Summary

Generic interfaces describe wrappers whose contents change. Next, generic classes.

Key takeaways
  • ApiResponse<T>
  • data: T
  • Many uses
Next up: Generic Classes — a typed list