← Back to TypeScript Course | Chapter 7: Generics | Lesson 3 of 8

Generic Interfaces

Generic interfaces define reusable object shapes that can work with different types. They are useful for responses, containers, collections, and other structured data.

Basic Generic Interface

An interface can declare a type parameter and use it inside its own property types, letting one interface definition describe many different concrete shapes depending on what type is supplied.

Example: Basic Generic Interface

typescript
interface Box<T> {
  value: T;
}
const numberBox: Box<number> = { value: 42 };
console.log(numberBox);

Generic Response Interface

A generic response interface can keep common metadata — like a status code or timestamp — fixed across every use, while allowing the actual data payload's type to vary per API endpoint.

Example: Generic Response Interface

typescript
interface ApiResponse<T> {
  status: number;
  data: T;
}
const res: ApiResponse<string> = { status: 200, data: "OK" };
console.log(res);

Generic Interfaces with Arrays

An interface can use a generic parameter to define the type of items in a collection, so a single Box<T>-style interface can describe a box of numbers, a box of strings, or a box of anything else.

Example: Generic Interfaces with Arrays

typescript
interface Box<T> {
  items: T[];
}
const box: Box<number> = { items: [1, 2, 3] };
console.log(box);

Generic Interfaces with Functions

Generic interfaces can describe functions whose input and output types vary together, which is useful for typing callback shapes that need to stay flexible across different call sites.

Example: Generic Interfaces with Functions

typescript
interface Transformer<T, U> {
  transform: (input: T) => U;
}
const toLength: Transformer<string, number> = {
  transform: (s) => s.length,
};
console.log(toLength.transform("hello"));

Generic Interfaces with Objects

A generic interface can contain a reusable object type selected by the caller, which avoids having to write near-identical interfaces over and over just because the contained data type changes.

Example: Generic Interfaces with Objects

typescript
interface Container<T> {
  content: T;
}
const container: Container<{ id: number }> = { content: { id: 1 } };
console.log(container);
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.