DEV Community

Cover image for TypeScript generics
Zalán
Zalán

Posted on

TypeScript generics

One of the most essential aspects of software development is writing reusable code. Your code must work with variable X and even with variable Y.
One of the most common ways you might know is writing methods. A well-written method without generics will only work with one specified type. For example this piece of code only works with integers.

function isEven(num: number): boolean {
  if (num % 2 == 0){
    return true;
  }
  return false;
}

But what if we want to use more types for the same method? That's what generics are used for. During our journey of learning TypeScript, you might have come across snippets like this:

let list: Array<number> = [1, 2, 3];

This Array type is using generics to only accept a certain type selected by you

But what is this < > thing?

We can use this syntax to give types to generics.

How can I create generic methods or classes?

We need a way of capturing the type of the argument in such a way that we can also use it to denote what is being returned. Here, we will use a type variable, a special kind of variable that works on types rather than values (we mostly call this variable "T").

function getRandomItem<T>(items: T[]): T {
  return items[Math.floor(Math.random() * items.length)];
}

Challenges

  • [Easy]: Write a generic method that swaps two values
  • [Medium]: Write a generic method to count the number of elements in a collection that have a specific property (for example: odd integers, prime numbers, etc..).
  • [Hard]: Write a linked list implementation with generics.

If you want more write a comment and follow me, thanks!

Follow me on twitter

Top comments (0)