Creating a Generic Function in TypeScript

Last updated on 11 Feb, 2023

We can create a generic function in TypeScript. That means, it will be a function that takes the argument and return type dynamically.

To understand better, here we have a normal typed function:

function fun(a: number, b: number): number {
  return a;

fun() function takes 2 numbers and returns a number.

Next, we need to make use of add() function to also return a string. For that we need to update the argument and return type as shown below:

function fun(a: number | string, b: number | string): number | string {
  return a;

But, when we write a function like above, the inputs can be a string and return can be a number.

How can we make it like, if the input is number type, return also should be number type. Same thing for string? For that, we can use generics.

function fun<T>(a: T, b: T): T {
  return a;

Now the type of function fun() is decided based on the type of argument passed to the function. Because of that you can see below that the first function invocation throws error, as division on strings are not allowed.

Error generic function
--- ○ ---
Joby Joseph
Web Architect