Generics?
Table of contents
Hello, Adarsh this side. Today, I have decided to go on a little adventure on the hills of Typescript and Generics is the topic where most slips. But all it needs a strong footing from preventing such happenings. So, let's get started.
First of all, Generics aren't custom to Typescript, Java has it, C# has it ( I guess). So this is not just a Typescript concept but yes, it was a breakthrough for Typescript when it was introduced.
Before knowing what Generics are in Typescript, let's get an idea on Typescript and what it intends to achieve. I will write more about Typescript for sure in upcoming articles but a summary here would be helpful to cement the understanding. Typescript is a super set of JavaScript and it intends to get rid of most common errors that are found in production, i.e. type errors or typos.
Building on that, Typescript has a lot of types along with the primary ones. It has a type by the name of any, undefined, never and many more. These list of types to ensure that while declaring variables, user must also provide its type to ensure type safety. Now, if you are a former JavaScript developer ( and I hope you are if you are reading this), functions that are passed and treated as arguments or variables are called High Order Functions. The type safety holds true for these special type of functions too.
One more interesting thing about Typescript is that it allows developers to create personalized data types. These custom data types are created in order to cater the need for the project.
Now, if I want to assign data types to functions, there some ways by which we can achieve this, stay with me,
by assigning each data type using OR operation,
by assigning "any" data type to provide access to every data type, but the dip here is that using "any" in the function as a data type would result in losing information about the data type that the function returned,
by using Generics.
Here is how to use the Generics to get rid of the above problem, use angular brackets (<>) after declaring function name and in between the angular brackets, we will name the type, either the custom, pre-defined types or just any keyword you want to use.
This allow us to have the same type throughout the function without using "any" data type and also maintains equality of data type.
But Generics is not limited to functions, it can also be used in classes or interfaces.
This pretty much sums up Generics in Typescript and now you can say that you have a strong foot hold at it. For coding examples or code snippets I will provide the link for the documentation below.
Go, Learn, Build, and Give Back.
Subscribe to my newsletter
Read articles from Adarsh Singh Tomar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by