How To Get The Return Type of a Function in TypeScript

TypeScript provides many powerful methods to work with data types, including ReturnType, which helps us get the Return Type of a Function. The article will show you how to do it. Let’s start together.

Get the return Type of a Function in TypeScript.

While working, you want to avoid hardcoding types in your code that can lead to errors but want to rely on a data type returned from a function. You can use ReturnType Utility and typeof operator.

ReturnType Utility Type

ReturnType in TypeScript language takes the return data type and constructs a new type. It is very useful when a function wants to receive data returned from another function.

Example:

In this example, we create a function that returns the string data type and then passes it to ReturnType. The newType variable will receive the return data type from the ReturnType and create a student variable with the newType data type.

// Use ReturnType to get the data type
type newType = ReturnType<() => string>;
const student: newType = "John";
console.log(typeof student);

Output:

string

Use ReturnType with the typeof type operator.

In JavaScript, you can use typeof to check the type in an expression context.

Example:

const name = "John";

// Using typeof in JavaScript
console.log(typeof name);

Output:

string

In TypeScript, you can use typeof to refer to the data type of a variable

Example:

let student = "John";

// Using typeof in TypeScript
let newType: typeof student;

newType will be of type string because of the reference from the student variable.

Combining the two, we can get the return Type of a Function in TypeScript

Example:

const GetName = (): string => {
    return "John";
};

// Using ReturnType with typeof
type newType = ReturnType<typeof GetName>;

newType will have a data type of string

To refer to the data type of the function GetName, we use the keyword typeof. Combined with the ReturnType utility, we will get the data type of the function and store it in the newType variable

Get the return type of an asynchronous function

For the asynchronous function, we need to use Awaited utility to wait for Promise to return from the function.

Example:

async function GetAPI(url: string) {
    const data = fetch(url);
    return data;
}

// Use Awaited utility to wait for Promise to return from the function
type newType = Awaited<ReturnType<typeof GetAPI>>;

newType will have a data type of promise

Summary

The article have show you how to get the return Type of a Function in TypeScript using ReturnType and typeof. Use it, and you will see no need to do many updates in the program. Please comment if you have any questions, we will be happy to answer.

Leave a Reply

Your email address will not be published. Required fields are marked *