Understanding Generics in Typescript

Photo by Michele Purin on Unsplash

Making our code resuable is something we all strive for, or at least we know that we should.

Consider the following function.

function identity(arg: number): number {
  return arg;
}

It doesn't really do anything, except helping me make a point. Takes in a number and returns it.

Let's say that we want to pass in a string. We could create a new function that accepts string arguments,

function identity(arg: string): string {
  return arg;
}

But what if we now wanted to pass in a boolean? Should we create another function? Maybe we can allow all types?

function identity(arg: any): any {
  return arg;
}

No... That's not what we want. We want  to return the same type that came in.

Generics let us do just that.

function identity<T>(arg: T): T {
  return arg;
}

So now, we could say

const output: boolean = identity<boolean>(true);

or

const output: number = identity<number>(1);

We could also call the function without the <type>

const output: number = identity(1);

If we do that, then the return type is automatically infered and this is call type inference.

Now that we know what generics are let's see how to use them to make our code more well... generic.

Next: Generics in classes and interfaces.

HashJar

HashJar