DEV Community

Alireza Razinejad
Alireza Razinejad

Posted on

1

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more