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

rahulrajrd image

Top comments (1)

Collapse
 
lukeshiru profile image
Luke Shiru

Generics not only work with methods, but with functions. And you can make it so the type system is way more useful by using string types and as const:

type Primitive = string | number | boolean | bigint | null | undefined;

const getStringFromTwoArray = <
    Array1 extends ReadonlyArray<Primitive>,
    Array2 extends ReadonlyArray<Primitive>,
>(
    [item1]: Array1,
    [item2]: Array2,
) => `${item1} ${item2}` as `${Array1[0]} ${Array2[0]}`;

const array1 = [1, 2, 3] as const;
const array2 = ["a", "b", "c"] as const;

getStringFromTwoArray(array1, array2); // Return type here is "1 a" instead of `string`
Enter fullscreen mode Exit fullscreen mode

Cheers!

🌚 Life is too short to browse without dark mode