DEV Community

Cover image for Create generic methods in TypeScript
Rahul Raj
Rahul Raj

Posted on

Create generic methods in TypeScript

Have you ever have to create methods where the return type is not predefined or is based on some input we give.
Consider the below:

  public getFirstItem(items: string[]): string {
    return items[0];
  }

  public logicX(): void {
    const item = this.getFirstItem(['alpha', 'beta', 'gama']);
    console.log(item) // 'alpha';
  }
Enter fullscreen mode Exit fullscreen mode

The above will return a string which will be assigned to items variable which is string.

What if you want to get first data of number array instead of string array. Like :

  public logicY(): void {
    const item = this.getFirstItem([1,2,3,4,5]);
    console.log(item);
  }
// You will get the below error
Type 'number' is not assignable to type 'string'.
Enter fullscreen mode Exit fullscreen mode

So what to do then.
The initial logic is to use union | symbol like:

public getFirstItem(items: string[] | number[]): string|number {
    return items[0];
  }
Enter fullscreen mode Exit fullscreen mode

This might solve your problem now but what if I want the first element from Boolean array. There will be again a modification needed to accommodate the Boolean parameter.

public getFirstItem(items: string[] | number[] | boolean[]): string|number|boolean {
    return items[0];
  }
Enter fullscreen mode Exit fullscreen mode

And the logic will go on and on 💤💤

Now there comes the generic method creation 😊. It will help us to decide the datatype while calling the method.

  public getFirstItem<T>(items: Array<T>): T {
    return items[0];
  }

  public logicX(): void {
    const item = this.getFirstItem(['alpha', 'beta', 'gama']);
    console.log(item) // 'alpha';
  }

  public logicY(): void {
    const item = this.getFirstItem([1,2,3,4,5]);
    console.log(item); // 1
  }

OR 
  public logicX(): void {
    const item = this.getFirstItem<string>(['alpha', 'beta', 'gama']);
    console.log(item) // 'alpha';
  }

  public logicY(): void {
    const item = this.getFirstItem<number>([1,2,3,4,5]);
    console.log(item); // 1
  }
Enter fullscreen mode Exit fullscreen mode

So now you can call the method and the Type will be automatically added or you can add the type whenever you are calling the method.

You can more than one Type and get the result like below:

  public getStringFromTwoArray<T, T1>(item1: Array<T>, item2: Array<T1>): string {
    return item1[0] + ' ' + item2[0];
  }
Enter fullscreen mode Exit fullscreen mode

Now in the above there will be to array whose datatype will be defined while calling.


Get to know about different array types

If you like the post follow me for more

Top comments (0)