Generic Interfaces: Basics
You'll learn: How to define interfaces with type parameters to create flexible, reusable contracts for objects with varying types.
What Is a Generic Interface?
A generic interface is an interface that accepts one or more type parameters, making it reusable for different data types while maintaining type safety. Instead of hardcoding specific types inside the interface, you declare placeholders that get filled in when the interface is used.
Think of a generic interface like a customizable blueprint: the structure stays the same, but you can swap out the materials (types) depending on what you're building.
Basic Syntax
Here's your first generic interface:
interface Box<T> {
value: T;
}
const numberBox: Box<number> = { value: 42 };
const stringBox: Box<string> = { value: "hello" };
The <T> after the interface name declares a type parameter. When you use Box<number>, TypeScript knows value must be a number. When you use Box<string>, value must be a string.
Why This Matters
Without generics, you'd need separate interfaces:
interface NumberBox { value: number; }
interface StringBox { value: string; }
With a generic interface, one definition works for all types, reducing duplication and keeping your code flexible.
Multiple Type Parameters
You can use multiple type parameters:
interface Pair<K, V> {
key: K;
value: V;
}
const entry: Pair<string, number> = { key: "age", value: 30 };
Key Takeaway: Generic interfaces let you define object shapes with type parameters, creating reusable contracts that adapt to whatever types you specify when using them.