Generic interfaces let you create flexible blueprints that work with many types, not just one. This helps you write code that can handle different data without repeating yourself.
Generic interface declaration in Typescript
interface InterfaceName<T> {
property: T;
method(param: T): T;
}The <T> after the interface name means it uses a generic type called T.
You can use any name instead of T, but T is common and stands for 'Type'.
Box holds one property content of any type T.interface Box<T> {
content: T;
}Pair uses two generic types T and U for two properties.interface Pair<T, U> {
first: T;
second: U;
}Result has a boolean success and a generic data of type T.interface Result<T> {
success: boolean;
data: T;
}This program defines a generic interface Container with a type T. Then it creates a class NumberContainer that uses number as the type. It stores a number and returns it with getValue. Finally, it prints the stored number.
interface Container<T> {
value: T;
getValue(): T;
}
class NumberContainer implements Container<number> {
value: number;
constructor(value: number) {
this.value = value;
}
getValue(): number {
return this.value;
}
}
const myNumber = new NumberContainer(42);
console.log(myNumber.getValue());Generic interfaces help keep your code DRY (Don't Repeat Yourself) by reusing the same structure for different types.
You can use multiple generic types separated by commas, like <T, U>.
When implementing a generic interface, you must specify the actual type to use.
Generic interfaces let you create flexible and reusable blueprints for data.
Use <T> to declare a generic type in an interface.
Implementations must specify the actual type to use with the generic interface.