DEV Community

Taric Ov
Taric Ov

Posted on

TypeScript: Generics… How about a pizza?

You love pizza, you eat pizza, you order pizza but they deliver “Generics”… you ordered sometin’?

Image description

Why you might choose to use TypeScript?

There are too many perks and benefits you can get from integrating typescript into your projects, but there are 2 reasons in specific that really concern and affect the whole development process and leverage the developer experience:

  1. Code Reliability: ⚓️
    TypeScript is a statically typed language that can help catch errors and bugs at compile time before your code is even run. This can lead to more reliable and predictable code, especially in larger projects.

  2. Code Maintainability: 🔧
    TypeScript’s type annotations can make your code easier to understand and navigate, especially for developers who are new to a codebase. Additionally, TypeScript’s features like interfaces and type aliases can help you create reusable, composable code.
    Put that in mind as you go in your Typescript journey and you will appreciate it. By the way, I will not talk much about any typing concepts in this article except Generics cuz i stumbled upon its (What is that???) and really want to demystify it so you can understand it better after i struggled a while.

What are generics?

Let’s first bring Pizza! 🍕

So imagine we got a pizza, a full-rounded pizza, and you told the pizzeria “Don’t cut it into pieces, i need it as a whole” Now you take it home, and in your kitchen, you got geometric shapes of cutters, e.g. triangles/rectangles/circles/stars/squares; all of these cutters you use to cut your pizzas to have fun sharing star-shaped pizzas w/ your pals.

But today, you have a big party and you may want to cut the pizza in a more formal yet free way so that you could cut smaller slices— or even cut each slice in a half and each half in a half Lol — so all can eat and enjoy .. NOW you know that you will have to bring a knife this time instead of those pre-defined specific shapes.

And here's the bottom line: Generics is the knife that you use to custom-cut pizzas .. that’s it.

It’s a tool you would use whenever you are uncertain about what types(shapes) you will use in a function(pizza)

After eating your pizza: How do generics work? 🤔

Generics use a special type variable called T and there are 2 points:

  1. It’s variable .. you know variables very well like const oneVariable or var anotherVariable;

  2. but the only difference, it’s a type variable, which means it’s only and all like if you do this: let variable2 = typeof "some string"

  3. The T here is just a convention, you could call it K it doesn’t matter.

  4. Now, this T is a type variable and it’s generic, and Oxford Dictionary says:

    Generic: means general, not specified .. got it?! (yes oxford said that)

  5. A generic type variable is like a parameter in functional programming that you could replace with arguments like so:

function add(x, y){ //x and y are parameters to place-hold for arguments
return x + y
}

add(3,4) //3 and 4 are arguments to test the function

Enter fullscreen mode Exit fullscreen mode

Code Example:

Let’s say you want to write ONE function that adds any 2 things together and still keep your code type-safe .. hmm

Remember ✋ we are talking all about types.

Before I learn Generics, I’d do this I would you could write a function for each type like this:

function addStr(a: string, b: string): string {
  return a + b;
}
function addNum(a: number, b: number): number {
  return a + b;
}

// Calling the functions 👇👇👇👇👇

addStr(1, 2); // 3
addNum("a", "b"); // "ab"

Enter fullscreen mode Exit fullscreen mode

But now and while I’ve been learning how to use a knife, I’d write it like that:

function add<T>(a: T, b: T): T {
  return <any>a + <any>b; 
//Type <any> here is just for escaping typescript infering unknown-ability
}
Enter fullscreen mode Exit fullscreen mode

This function now can add any 2 things together, as long as both are the same type. For example, you could call it like this:

add(1, 2); // 3
add("a", "b"); // "ab"
add({name: "John"}, {age: 10}); // {name: "John", age: 10}

Enter fullscreen mode Exit fullscreen mode

and if you imagined that you could do this add(2, "4") .. now you are getting that error:

ERROR: Argument of type ‘4’ is not assignable to parameter of type ‘2’

Meaning that your types are safe even when you are not sure of the inputs and their type.

So Why generics? I thought you know by now!

You know by now why, right? but let’s list the benefits:

  1. Generics allow you to write code that is more 🔄 reusable,

  2. Generics allow you to write code that is more ✅ type-safe,

  3. The compiler checks for the types of arguments you pass to the function and make sure they are compatible, avoiding errors in ⚡️ Compile time and even before running your app ⚡️

  4. The compiler infers the type of T and this enables auto-completion to suggest only the available right options ✋

example: When you call the add function, as previously shown, with two numbers, the compiler will infer that the type of T is number, thus the auto-completer will complain when you use any other types other than numbers. MAGIC ha!

That’s it for today, till next time.. see ya 👊😉

Top comments (0)