Generic in Typescript
Generics:
Even for developers with experience, generics are sometimes confusing. Let’s finally make it simple and clear.
Genric means 'relating to a whole group of similar things'
The main use of generics has provided type safety, re-usability, error handling, and increase the performance also provide compile time type safety and that allow the programmer to check catch invalid type at compile time
the reason is that we cannot perform type checking at compile time and that will cause big problems when code increase.
for example, when we do not use generic that time what is going on
in the above example, there is a function called 'add1 ()' it takes to parameter one is 'x' and other is 'y' and return addition x+y.in console.log we call function add (1,2) after that we call add1 ("1","2") and lest we call add1 ('1','two'). so the output is shown there here we observe that there is no type safety, we can add integer and string so there is problem that at such case this shouldn't be like this that may causes big problem when we store the amount of data and retrieve it because we don't get correct data.
so the solution is generic
In this example we have used <T> which is a Generic Type Variable. Now the question is how do you tell TypeScript what exactly T is. The answer is when we are instantiating a class using new GenericsExample<string>(); we are specifying the type of T (string in this case). Now you can understand the beauty of Generics is that if we need a same class to behave similarly with different data type we do not have to write it multiple times we can simply use Generics