How To Declare a Function With a Promise Return Type in TypeScript

In order to avoid errors arising during the application run, we should explicitly declare a Promise return type. To do so, we will use Promise syntax after the parameters. This article will give specific examples of different uses of the function.

Declare a function with a Promise return type in TypeScript

To do so, we will declare the return type of the Promise after the declaration of the function parameters separated by a colon. We will give examples of different types of functions in TypeScript.

Declare in a regular function

We will use the following syntax to add the following after declaring the function parameters.

Syntax:

Promise<type>

Parameters:

type: here, we will specify the type that a Promise should return, if not specify the type then TypeScript will guess by itself.

Example:

type price = {
    price: number;
};

// We will declare Promise<price> right after the parameter declaration
function getPrice(price: number): Promise<price> {
    return Promise.resolve({ price: price });
}

const myPrice = async () => {
    const price = await getPrice(199);
    console.log(price);
};

myPrice();

Output:

{ price: 199 }

In the above example, we declare a data type as the price of the product. Then we will get the price of this product on the backend server. In this example, we only pass the price of 199. Not explicitly declaring the data type of Promise very easy to leads to runtime error, which is a very dangerous and difficult error to fix, so we declare Promise right after the declaration of the parameters in the function.

Declare in an arrow function

The arrow function is a new style of writing function. We can write a function on a single line, so it is very useful in many cases. To declare a Promise in this function form is no different from declaration of a regular function

Example:

type price = {
    price: number;
};

// We will declare Promise<price> right after the parameter declaration
const getPrice = (price: number): Promise<price> => {
    return Promise.resolve({ price: price });
};

const myPrice = async () => {
    const price = await getPrice(199);
    console.log(price);
};

myPrice();

Output:

{ price: 199 }

In this second example, we’ve turned the regular function into an arrow function, and the Promise return type declaration is not very different. We just need to add after the colon

Summary

To summarise, to declare a function with a Promise return type in TypeScript, we will add the Promise syntax after the function parameter declaration. This is the only way that TypeScript provides us. We should declare explicitly and unambiguously to avoid errors occurring during runtime.

Leave a Reply

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