How to use the type keyword In Typescript

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("w3wiki"));
console.log("Workforce:" + double(100));


Output:

w3wiki
Workforce: 200

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

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.

Table of Content

  • Using the type keyword
  • Using the interface keyword

Similar Reads

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....

Using the interface keyword

...