DEV Community

πŸ› οΈ πŸ“¦ TypeScript Generics - a cheat sheet

Audrey Kadjar on August 15, 2024

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...
Collapse
 
bendman profile image
Ben Duncan

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:

// A generic function that works with any data type
function identity<T>(arg: T): T {
    return arg;
}

// Using the generic function with different types
let num = identity(42); // T is number
let str = identity("Hello"); // T is string
Enter fullscreen mode Exit fullscreen mode
Collapse
 
audreyk profile image
Audrey Kadjar • Edited

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.

Collapse
 
devto2k5 profile image
dev procedure • Edited

ARE GENERICS REALLY USEFUL in the REAL WORLD?

Generics enable you to define a type variable that serves as a placeholder for a specific type to be provided later. This is the core strength of Generics: they allow you to define flexible, reusable types without sacrificing type safety.

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?

Collapse
 
levan_gharibashvili_7fcac profile image
Levan Gharibashvili

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.

Collapse
 
bendman profile image
Ben Duncan

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.

Collapse
 
audreyk profile image
Audrey Kadjar • Edited

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.

Collapse
 
devto2k5 profile image
dev procedure • Edited

The responses to defend generics and saying there are use cases only refer BACK to built-in functions, that is,

most array methods, set methods, map methods, etc.

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.

Thread Thread
 
steve-oh profile image
Steve Schafer • Edited

But that is NOT the REAL world of PHYSICAL products or services, like stuff you buy at Home Depot or Walmart.

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.

Thread Thread
 
devto2k5 profile image
dev procedure

The point of generics here is that sometimes I need to know whether a screw is a Screw vs. a Screw (e.g., thread specifications for wood screws and machine screws are different),

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.

Thread Thread
 
steve-oh profile image
Steve Schafer

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.

Collapse
 
oatula profile image
Atul Anand Oraon

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.

Collapse
 
wizard798 profile image
Wizard

Yes, it's definitely useful for a person who's learning ts currently, thanks for this tips

Collapse
 
jwp profile image
John Peters

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.

Collapse
 
yves_denels_ecfa97d4db595 profile image
Yves Denels

Weren't generics first implemented in Java?

Collapse
 
audreyk profile image
Audrey Kadjar
Collapse
 
kevineverywhere profile image
Kevin Ready

Thank you for demystifying a basic ingredient in TypeScript succinctly. Great article!

Collapse
 
audreyk profile image
Audrey Kadjar

thanks @kevineverywhere :)

Collapse
 
alexanderop profile image
Alexander Opalic

really nice blog post that shows the core concepts of generics

Collapse
 
audreyk profile image
Audrey Kadjar

thanks @alexanderop :)

Collapse
 
tungtrangn profile image
Trang Tung Nguyen

Great article! Thanks for sharing!

Collapse
 
audreyk profile image
Audrey Kadjar

thanks @tungtrangn :)

Collapse
 
enderakay profile image
Ender Akay

Very helpful thanks!

Collapse
 
audreyk profile image
Audrey Kadjar

thanks @enderakay :)

Collapse
 
oatula profile image
Atul Anand Oraon

This is really awesome πŸ‘.
Lots of learning

Collapse
 
jangelodev profile image
JoΓ£o Angelo

Hi, Audrey Kadjar!
Thanks for sharing
Great article

Collapse
 
audreyk profile image
Audrey Kadjar

thanks @jangelodev :)

Collapse
 
audreyk profile image
Audrey Kadjar

thanks @wizard798!!

Collapse
 
amir7mou profile image
Amir 1998

πŸ™β€οΈπŸ€©βœ…πŸ˜Žβ€οΈ

Collapse
 
audreyk profile image
Audrey Kadjar • Edited

thanks @amir7mou :) love this emoji combo!

Collapse
 
eslachance profile image
Lucas Lachance

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 as Key , V as Value , and T as CustomType or something? Are you all afraid of writing longer names? Do you name all your variables a, b, c, d ?

Collapse
 
eslachance profile image
Lucas Lachance
interface U {
  n: string;
  a: number;
  l: string;
}

//makes all properties optional 
const pU: Partial<U> = {n: 'Alice'}

//allows to omit properties: here the name property is omitted
const oU: Omit<U, 'n'> = {l: 'Berlin', a: 33}
Enter fullscreen mode Exit fullscreen mode

This is how you're writing generics, guys. Stop it.

Collapse
 
bh4skar profile image
Bhaskar Prajapati

Definitely can be more refined. It is covering just the very beginner concept.

Collapse
 
jasonona profile image
JasonOna

How would you refine this? What would you like to include?

Collapse
 
audreyk profile image
Audrey Kadjar • Edited

@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?

Collapse
 
xcfio profile image
xcfio

You forgot to add example of implicit generic.

Collapse
 
santiagoarizti profile image
Santiago Arizti

Nice article, but this is not a cheat sheet, more like a tutorial.

Collapse
 
ofek_shilon_acde8a5e80902 profile image
Ofek Shilon

Without further constraints, Pair can be instantiated with identical types for both arguments.

Collapse
 
audreyk profile image
Audrey Kadjar • Edited

@ofek_shilon_acde8a5e80902 yes, you are correct! I've added an example to illustrate this.

thanks for reading the article :)