Creating interfaces with generic types in TypeScript is a powerful feature that enhances code flexibility and reusability. By defining interfaces with generic type parameters, you can create components that work with various data types while maintaining type safety.
Interface with a Single Generic Type Parameter
Syntax
interface InterfaceName<T>
{
// Interface members
}Defining an interface with a single generic type parameter allows for the creation of versatile components that can operate on different data types interchangeably. This approach enhances code flexibility and promotes code reuse by abstracting away specific data implementations.
Example: The below code creates an interface with a single generic type parameter.
interface Box<T> {
getItem(): T;
setItem(item: T): void;
}
class MyBox<T> implements Box<T> {
private item: T;
getItem(): T {
return this.item;
}
setItem(item: T): void {
this.item = item;
}
}
const stringBox: Box<string> = new MyBox < string > ();
stringBox.setItem("Hello, Generics!");
console.log("String Value:", stringBox.getItem());
Output:
String Value:, Hello, Generics!
Multiple Generic Type Parameters
TypeScript also supports interfaces with multiple generic type parameters, enabling developers to design highly customizable and parameterized components.
Example: The below code creates an interface with multiple generic type parameters.
interface Pair<K, V> {
key: K;
value: V;
}
const pair: Pair<number, string> =
{ key: 1, value: "One" };
console.log("Key:", pair.key,
", Value:", pair.value);
Output:
Key: 1, Value: One