Generics in TypeScript can seem daunting at first - whatβs with all those capital letters and square brackets? π
But donβt worry, this cheat sheet...
For further actions, you may consider blocking this person and/or reporting abuse
You don't actually need to call the identity function with a type like in your example.
It will infer the type from the argument, so unless you need to override an incorrect inference you can just call it like normal:
thanks for your comment @bendman :)
yes, you are correct. I am aware of this, but in my examples, I specified the types because I wanted to highlight how TypeScript handles different types with generics. I've added a note about this in my article to clarify this.
ARE GENERICS REALLY USEFUL in the REAL WORLD?
Let's think about the value of Generics. Are we really going to have a variable, a class, or a function where we have NO IDEA of the data that they should handle???
When we initially give a variable a name, we should give it a GOOD NAME right off the start.
But Generics would allow for VAGUE variable names as you say you don't really know what "type" the variable will handle, and we can decide later. Is that really a good thing? Not having any idea of what kind of data your variable is going to handle?
If you don't even know what kind of data your variable is going to handle, can you even give that variable a GOOD DESCRIPTIVE NAME to begin with?
Does Generics allow for "half-baked programming and design" to happen?
You are not correct. There's lots of use cases for generics. For example collections: Array, Set, Map are all generic. They can work with any type and the semantics are same. You might have array of numbers, array of strings or array of certain objects. Without generics you would need to create separate Array classes for each type.
Regarding naming, yes you can still give variables good names. For example, in Array.push method you would have an 'element' parameter. Even though it doesn't have a concrete type, the name is still descriptive.
Generics have nothing to do with naming, and are more about writing functions that work on different argument types and return a properly constrained type based on the input.
Many utility functions work for different types. Nearly all built-in utility functions are generics: most array methods, set methods, map methods, etc.
Imagine you want to make a new utility that takes a function with a callback and converts it to async/promise function, and returns the correct type at the end. This is trivial with generics and impossible without.
thanks for reading the article & your comment @devto2k5!
I agree with @levan_gharibashvili_7fcac. There are a lot of use cases for generics: they are powerful because they allow flexibility without sacrificing type safety.
Generics are not about having "no idea" of the data being handled; they are about designing systems that can handle a variety of types in a structured, predictable manner.
The responses to defend generics and saying there are use cases only refer BACK to built-in functions, that is,
But that is the Framework, Library World of making more functions, variables.
And where you have NO IDEA of what the variable name or function will be.
That is, The Framework and Library World.
But that is NOT the REAL world of PHYSICAL products or services, like stuff you buy at Home Depot or Walmart.
NOTE: We just had 3 responses (to my comment) defending generics, but none actually gave a REAL world examples.
Sure it is. When I go to Home Depot to buy some screws, I go to the screws section, which contains all manner of screws. Different screws have different properties, but many of them share values of those properties. For example, Screw<Wood> has a certain shape, which is very different from the shape of Screw<Machine>. The point of generics here is that sometimes I need to know whether a screw is a Screw<Wood> vs. a Screw<Machine> (e.g., thread specifications for wood screws and machine screws are different), and other times I just need to know that it is a Screw<T>, where T remains unspecified (e.g., screw material, length, and quantity per package are not dependent on whether a screw is a wood screw or a machine screw).
When I'm buying screws at Home Depot, I'm not literally classifying them into generic types the way I would if I were writing a software application, but I am effectively doing that as I search for the screws that I need.
But since you already know that Wood Screws are different than Machine Screws AND you know the properties of each type of screw, WHY would I need to use generics?
Couldn't you just describe each screw's properties in the DATABASE (as you would have to anyway?) and use a few look-up tables for each screw type?
And if I wanted to add a new screw type, why wouldn't I just take an existing screw type, and modify that one? Via Copy and Paste?
Also, any major app is going to have to save to a database anyway, so are you going to save "vagueness" to the database? Isn't it just real stuff, important stuff that is worth saving to a database?
Using Generics for screws seems like a waste of time and adds a layer of complexity that has essentially zero benefits, short-term or even long-term.
That is, I would NOT need to decipher stuff like
and hence I would not need a "cheat sheet" as I could read the code far more easily.
You're completely missing the point. Generics aren't about what's different; they're about what's the same. If I want to sort an array of screws by length, having separate WoodScrew.SortByLength() and MachineScrew.SortByLength() methods is just duplicating code. Instead, I define an ISortableByLength interface, and the vast majority of different kinds of screws can use a single implementation that only cares about length.
Interesting perspective.
I won't support nor oppose your suggestions.
I too had similar thoughts starting with Typescript.
But I needed to use it.
Especially on the frontend for the React as the functions expect the elements to be passed like,
HTMLElement<Something>
It's something we can't escape.
Yes, it's definitely useful for a person who's learning ts currently, thanks for this tips
Yes generics, first implemented in C# opened the door for using common methods to process lists of any type. A list of Person would also work on a list of an item, to sort, to order, to reverse, to allow functional support for anything.
Unlike Javascript arrays, type safety in Generics prevented unintended consequences.
In the end it's all a contract of behaviors applied liberally across types.
Why experience runtime failures when not needed?The compiler becomes a best friend to programmers with no need for linting.
Weren't generics first implemented in Java?
yeah I think they were first implemented in Java in 2004.
Thank you for demystifying a basic ingredient in TypeScript succinctly. Great article!
thanks @kevineverywhere :)
really nice blog post that shows the core concepts of generics
thanks @alexanderop :)
Great article! Thanks for sharing!
thanks @tungtrangn :)
Very helpful thanks!
thanks @enderakay :)
This is really awesome π.
Lots of learning
Hi, Audrey Kadjar!
Thanks for sharing
Great article
thanks @jangelodev :)
thanks @wizard798!!
πβ€οΈπ€©β πβ€οΈ
thanks @amir7mou :) love this emoji combo!
If Typescript developers could please stop writing Generics as if they were writing pre-minified code, that would be great.
What's the problem with defining
K
asKey
,V
asValue
, andT
asCustomType
or something? Are you all afraid of writing longer names? Do you name all your variablesa, b, c, d
?This is how you're writing generics, guys. Stop it.
Definitely can be more refined. It is covering just the very beginner concept.
How would you refine this? What would you like to include?
@bh4skar I wanted to write a short article about generics to lay out the fundamentals. This article doesn't pretend to be exhaustive. I'm also curious: what would you like to include?
You forgot to add example of implicit generic.
Nice article, but this is not a cheat sheet, more like a tutorial.
Without further constraints, Pair can be instantiated with identical types for both arguments.
@ofek_shilon_acde8a5e80902 yes, you are correct! I've added an example to illustrate this.
thanks for reading the article :)