Generics in TypeScript
Because we don’t know what type the user will use!
Generics are a big part of programming. They allow us to write type-safe functions without even knowing what the actual type will look like. But we can set certain restraints on the types a programmer might use.
In this article, I will explain generics in TypeScript and how to use them. The only prerequisite of this article is a little bit of TypeScript knowledge. I will keep it as simple as possible. But because the topic at hand doesn’t have to be difficult, this article will be pretty short.
Generics in TypeScript
I will use this site to play around with TypeScript and organize the code I show here in Gists for ease of reading.
Now, in the case of a simple additive function like this, it will not be weird to only want to accept numbers. However, functions like
.filter() might not want to accept every array. Let's take a look at a simple filter function’s type definition.
Just imagine that this would be a good way to write a map function.
As this is written, it would only serve arrays filled with type
number . But what if the function is written in such a way that it could serve every type or just every type of array? We might still want to have type checking in some way. We know it’s an array, just not what kind of array.
We can write our function like this, using generics. The angular brackets
<> allow us to enter a name for our ‘unknown’ type.
But it becomes even better because we can add restrictions on our unknown type. Let’s look at the next example.
In this example, we have a basic greet function. But we don’t know if we’ll greet a
cat , a
person , a
fish , or something else that has a name. We just know we want to greet them.
So we create a type or an interface that always has the properties you’ll use inside of your function (or class!) and define our generic to extend that type or interface so it’ll always have the properties that you’re using.
This is just a very basic example of what generics can do. But with a little imagination, you can think of how powerful this can be in terms of maintainability and security.
If you want to learn more, you can read a ton on the official docs.
I hope that this was useful for some of you! Please check out my other articles on topics ranging from smart contracts to basic programming if you’ve enjoyed this one!
Thank you so much for reading and have an excellent day.
Consider supporting me by getting a Medium membership. It helps me out a lot, it won’t cost you anything extra, and you can read as many Medium articles as you like!
Follow me on Twitter and gm.xyz to keep up with me and my projects.
Check out Pixel Pizzas on the Polygon Blockchain.