Introduction

Sometimes you come across a situation to repeat the same block of code for different types. So, instead of writing repeated blocks of code, generics let you write a generalized form of method.

In languages like C# and Java, one of the main tools in the toolbox for creating reusable components is generics, that is, being able to create a component that can work over a variety of types rather than a single one. This allows users to consume these components and use their own types

Generics can be applied to functions, interfaces and classes in Typescript.

Links:

Generic function

function foo<T>(arg: T): T {
	
	// ... ... ...

    return arg;
}

Generic class

class Foo<T> {

	x: T;
	
	bar(y: T): T {
	
	}
}

Generic type constraints

class Foo<T extends U> {

	x: T;
	
	// ... .... ...
}