How to Type an Async Function in TypeScript ?
Last Updated :
13 Jan, 2024
To type an asynchronous function in TypeScript, you can use the Promise
type to denote that the function returns a promise.
Syntax:
async function functionName(parameters: ParameterTypes): Promise<ReturnType> {
// Asynchronous logic here
return await someAsyncOperation(); // or any other asynchronous logic
}
async
: The async
keyword declares that the function is asynchronous.functionName
: Replace with the desired name of your asynchronous function.parameters
: Replace with the parameters your function takes, if any.ParameterTypes
: Replace with the actual types of your function parameters.Promise<ReturnType>
: Indicates that the function returns a promise with a specific type (ReturnType
). Replace ReturnType
with the actual type of the resolved value.await
: The await
keyword is used inside the asynchronous function to pause execution until the promise is resolved. It is used in conjunction with asynchronous operations that return promises.
Approach:
- Use
async
Keyword: Prefix the function declaration with the async
keyword to indicate that it is an asynchronous function. - Specify the Return Type as
Promise<T>
: Specify the return type of the function as Promise<T>
, where T
is the type of the resolved value.
Example 1: We define an asynchronous function named exampleAsyncFunction
. The function returns a promise (Promise<string>
) that will eventually resolve into a string "Hello, TypeScript!"
. The use of async
and Promise<string>
ensures that the function is treated as asynchronous and is expected to return a promise containing a string.
JavaScript
async function exampleAsyncFunction(): Promise<string> {
return "Hello, TypeScript!";
}
const a = exampleAsyncFunction();
console.log(a);
Output:
Promise { 'Hello, TypeScript!' }
Example 2: We declare an asynchronous function asyncFunctionWithParams
that accepts two parameters: param1
of type number
and param2
of type string
. The function returns a promise (Promise<number>
) that resolves to the result of an asynchronous operation, in this case, the sum of param1
and the length of param2
. The use of async
and Promise<number>
indicates that the function is asynchronous and returns a promise containing a numeric value.
JavaScript
async function asyncFunctionWithParams(param1: number,
param2: string): Promise<number> {
// Async logic here
return param1 + param2.length;
}
const a = asyncFunctionWithParams(4, "hello");
console.log(a);