Open In App

How to Create a Generic Type Alias for a Generic Function in TypeScript ?

Last Updated : 23 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, it is possible to create a generic type alias for a generic function. A generic type alias provides a descriptive name for a function with generic parameters, making it easier to understand the code. It also makes the code reusable and readable especially when you are dealing with complex type structure.

Using the type keyword

In this approach, we define a type alias using the type keyword. The alias contains the generic function signature, including its parameter and return type, while also making it generic so that it can operate on different types.

Syntax:

type MyFunction<T> = (arg: T) => T;

Example: The below code example will explain the use of the type keyword to create a generic type alias.

Javascript




type MyFunction<T> = (arg: T) => T;
 
const double: MyFunction<number> =
    (x) => x * 2;
     
const capitalize: MyFunction<string> =
    (str) => str.toUpperCase();
 
console.log(capitalize("GeeksForGeeks"));
console.log("Workforce:" + double(100));


Output:

GEEKSFORGEEKS
Workforce: 200

Using the interface keyword

In this approach, we create a generic type alias for a function using the interface keyword. TypeScript Interfaces are typically used to define the structure of the object, however, we can use it to describe function signatures as well.

Syntax:

interface MyFunction<T> {
(arg: T): T;
}

Example: The below code will explain the use of interfaces to create a generic type alias for a generic function in TypeScript.

Javascript




interface MyFunction<T> {
    (arg: T): T;
}
const increment: MyFunction<number> =
    (num) => num + 1;
const reverse: MyFunction<string> =
    (str) => str.split("").reverse().join("");
console.log("Workforce: " + increment(199));
console.log(reverse("GeeksForGeeks"));


Output:

Workforce: 200
skeeGroFskeeG


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads