DEV Community

Alireza Razinejad
Alireza Razinejad

Posted on

Introduce new type using a function return type

In TypeScript, you can introduce a new type using the type keyword or using an interface. If you want to define a new type based on a function return type, you can use the ReturnType utility type.

Here's an example:

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

type SumResult = ReturnType<typeof calculateSum>;

const result: SumResult = 5;
console.log(result); // Output: 5
Enter fullscreen mode Exit fullscreen mode

In this example, we have a function calculateSum that takes two numbers and returns their sum. We can use the ReturnType utility type to capture the return type of the function, which in this case is number. Then, we create a new type SumResult based on the return type of calculateSum.

You can use the SumResult type to declare variables, function return types, or any other place where a type is expected. In this case, we assign the value 5 to a variable result of type SumResult, which is number, and then print it to the console.

This way, you can introduce a new type based on a function's return type using the ReturnType utility type in TypeScript.

Top comments (0)