Open In App

How to Create an Interface with Generic Type ?

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, creating interfaces with generic types is a powerful feature that allows developers to write flexible and reusable code. By defining interfaces with generic type parameters, TypeScript enables the creation of components that can work with a variety of data types while maintaining type safety.

Interface with 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.

Javascript




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.

Javascript




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 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads