TypeScript | Generic Function

TypeScript | Generic Function

·

4 min read

Introduction:

A good coding practice is to write reusable, flexible and scaleable code.

In TypeScript, a generic is a way to define a type or function that can work with multiple types, rather than being specific to a single type. This allows for more flexibility and reusability in your code.

It means we can create functions and classes that can work with a variety of data types.

Generic Function

Let's write a function to add two numbers.

function add(a:number, b:number):number{
    return a + b;
}

What if we need a function that adds two strings? We can't reuse this add function, because it takes number-type parameters. We have to define another function that takes string arguments.

function addString(a:string, b:string):string{
    return a + b;
}

This is not a good practice. We are repeating the same functionality at two places. If we could write a function that can work with both string and number types, then it would be much better.

The generic function is a way to solve our problem.

Let's see how to write a generic function with an example. A generic function takes a Type variable in an angle bracket(<>) after the function name.

function add<Type>(a:Type, b:Type):Type{
    return a + b;
}

This Type variable capture the type of parameters.

The Type is simply a variable, you can name it whatever you like. Normally, most developers name it as T .

Now, when we call this generic add function, we need to pass the type of arguments along with values.

let sum = add<number>(1,2); // 
let fullName = add<string>("Jhon", "Smith");

In the above example, we are passing arguments types [ defined in angle brackets <> ] along with arguments value. The Type variable captures the type from type arguments and assigns it to function parameters.

There is another way to call the function with type inference. We can let the typescript compiler decide the types of arguments.

let sum = add(1,2); 
let fullName = add("Jhon", "Smith");

The above code looks simple and easy to read. But sometimes in complex examples, the typescript compiler fails to infer the type of arguments, and then we have to explicitly write the types of the arguments.

Application of generic function

There are many real-world applications of generic functions in software development.

  1. Sorting an array of any type

  2. JSON parsing generic function

  1. Sorting an array of any type

Here's an example of a generic function that sorts an array of elements:

function sortArray<T>(arr: T[]): T[] {
    return arr.sort((a:T, b:T) => a > b ? 1 : -1);
}

let numbers = [14, 13, 30, 11, 2];
console.log(sortArray(numbers)); // output: [1, 2, 3, 4, 9]

let strings = [ "cherry","apple", "banana" ];
console.log(sortArray(strings));// output: ["apple","banana","cherry"]

In the above example, the sortArray function is defined as a generic function, with a type variable T. The function takes in an array of elements of type T and returns an array of elements of the type T .

As you can see, the function is defined once but it can be used for different types of arrays. This is the power of generics, it allows the same function to work for multiple types.

2. JSON parsing generic function

Here's an example of a generic function that parses a JSON string into an object of any type:

function fromJson<T>(json: string): T {
    return JSON.parse(json);
}

/*--------------------Example-1------------------------------*/
interface IUser {
    name: string;
    age: number;
}

let jsonString = '{"name":"Jack","age":25}';
let user = fromJson<IUser>(jsonString);
console.log(user.name); //output: "Jack"
console.log(user.age); //output: 25

/*----------------------Example-2---------------------------------*/
interface IProduct {
    id: number;
    name: string;
    price: number;
}

let jsonString2 = '{"id":1,"name":"Phone","price":200}';
let product = fromJson<IProduct>(jsonString2);
console.log(product.id); //output: 1
console.log(product.name); //output: "Phone"
console.log(product.price); //output: 200

In the above example, the fromJson function is defined as a generic function, with a type variable T. The function takes in a JSON string and returns an object of the type T.

In this example, we are using two different interfaces IUser and IProduct to define the structure of the objects.

In the first example, we are using IUser interface and passing the JSON string which is matching the structure of the IUser and it will return the object of the IUser type.

And in the second example, we are using IProduct interface and passing the JSON string which is matching the structure of the IProduct and it will return the object of the IProduct type.

Summary:

In this article, we learned what is a generic function in TypeScript. How generic functions help us reusable code. And a few applications of generic functions.

I hope this article helps you in your coding journey. In the next article, I will write about generic classes.

Thanks :)