Open In App

How to use generics in TypeScript?

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, the generics are used to create the reusable and type-safe components allowing you to pass the types as parameters to them. The generics are mostly used to create components with Functions, Interfaces, and Classes to make them work with any type of values passed by the users at the time of using them.

Syntax:

// Using with interfaces
interface interface_name<T1, T2>{
key1: T1;
Key2: T2;
}
// Using with functions
function function_name<T>(argument: T): T {
// Function Statement
}
// Using with classes
class class_name<T> {
// Class Statements
}

Example: The below code implements the generic interface in TypeScript.

Javascript




interface myInterface<T1, T2> {
    name: T1;
    desc: T1;
    est: T2;
}
 
const obj: myInterface<string, number> =
{
    name: "GeeksforGeeks",
    desc: "A Computer Science Portal",
    est: 2009
}
console.log(obj);


Output:

{
name: "GeeksforGeeks", 
desc: "A Computer Science Portal", 
est: 2009
}

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads