Generic Interfaces
In this page:
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
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
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
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
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
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: