Generics in TypeScript

In TypeScript Generics allows us to pass a range of types to a function or component. We can call it Abstract Type.

Let’s look at the example below.

function removeItem(arr: Array<number>, item: number): Array<number> {
  let index = arr.findIndex(i => i === item);
  arr.splice(index, 1);
  return arr;
}

let items: Array<number> = [1, 2, 3]
console.log(removeItem(items, 2));

As you can see that we are passing two parameters to the function, in that example it’s easy to say the return type should be an Array of numbers. But what about our removeItem() function doesn’t know about the type? Let me explain.

function removeItem(arr: Array<number>, item: number): Array<number> {
  let index = arr.findIndex(i => i === item);
  arr.splice(index, 1);
  return arr;
}

let items: Array<number> = [1, 2, 3]
let users: Array<string> = ['John', 'Mark', 'Adam']
console.log(removeItem(users, 'Mark));

Immediately TypeScript compiler throws an error saying,

Type ‘string’ is not assignable to type ‘number’.

So in order to make our function understand types abstractly, we need to use Generic.

function removeItem<T>(arr: Array<T>, item: T): T[] {
  let index = arr.findIndex(i => i === item);
  arr.splice(index, 1);
  return arr;
}

let items: Array<number> = [1, 2, 3]
let users: Array<string> = ['John', 'Mark', 'Adam']
console.log(removeItem(items, 3))// [1, 2]

console.log(removeItem(users, 'Mark'))// ['John', 'Adam']

In the removeItem() function we write <T> as a type variable before declaring the parameters, this can be anything(A, B, C, D..) and this allows us to capture the type the user provides. As we get the type <T> now we can set the type of the parameter and return type.

Leave a Reply

Your email address will not be published. Required fields are marked *