TypeScript Generics

In this section, we will learn about Typescript Generics.

Generics in Typescript are no different than generics in other programming languages like C# or Java.

You can create a class, an interface, or a function that works with different types, without specifying the type upfront.

TypeScript Generics Syntax

Let’s create a function with generic type:

function greet(a : T) {
  console.log(`Hi ${a}!`)
}

greet('DS'); //function call

The symbol T identifies a generic type.

Note: It is not required to use T as a type parameter. You can give any name to a type parameter.

We may restrict the type to a class or an interface using the extends keyword.  Let us show you with the help of an interface example:

interface IGreet 
{ 
   Name: string 
}

function greet<T extends IGreet>(a : T) {
  alert(`Hi ${a.name}!`)
}

greet({ Name: 'Tutorials Nest'}); //function call

Generic Interface

We can create a generic interface in typescript.

interface IStudent 
{ 
    result:T;
    process(a: T, b: T) => T;
}

Generic Class

A generic class in typescript would look like:

class Programmer {
   
   private languageName: string;
   private languageInfo: T;
constructor(lang: string) {
      this.languageName = lang;
   }
   ...
}

let programmer1 = 
   new Programmer("Typescript");
let programmer2 = 
   new Programmer("C#");

Let’s have a look at the resources to learn typescript in our next section.