Open In App

Typescript Awaited<Type> Utility Type

Last Updated : 19 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about the Awaited<Type> in TypeScript. It is a programming language that is a strict syntactical superset of JavaScript. It adds optional static typing and class-based object-oriented programming to JavaScript, one of the features of the typescript is Awaited<Type> it is a utility type in TypeScript that is used to extract the type that is being returned by a promise. It is useful when we want to work with the resolved value of a promise, rather than the promise itself. It helps us to avoid using .then() and await the same promise repeatedly.

Syntax:

type Awaited<Type>

Where –

  • Type represents the type of promise.

 

Example 1: In this example, we are going to use the awaited utility type to extract the resolved type of the Promise returned by the getUser function. We have defined the getUser function with the async keyword, which means it will always return a Promise. 

Javascript




async function getUser(): Promise<{ 
    id: number; 
    name: string 
}> {
    return { id: 1, name: 'John Doe' };
}
  
type User = Awaited<ReturnType<typeof getUser>>;
  
async function printUser(): Promise<void> {
    const user: User = await getUser();
    console.log(user);
}
  
printUser();


Output:

{
      "id": 1,
      "name": "John Doe"
}

Example 2: In the above example, we will use Awaited<Type> with Promise.all() to extract the resolved values of an array of promises. We will define an async function getUsers() that returns a promise with an array of user objects. We define a type User using Awaited<Type> to extract the resolved value of the promise and access the first element of the array, now then define another async function getUserNames() that extracts the names of the users using Promise.all() and await, as we can see in the working code below.

Javascript




async function getUsers(): Promise<Array<{ name: string }>> {
    const response = await fetch(
        "https://...com/users");
    return response.json();
}
  
type User = Awaited<ReturnType<typeof getUsers>>[0];
  
async function getUserNames() {
    const users = await getUsers();
    const names: Array<string> = await Promise.all(
        users.map(async (user: User) => {
            const name = user.name;
            return name;
        })
    );
    console.log(names);
}
  
getUserNames();


Output:

[
    “Leanne Graham”, “Ervin Howell”, “Clementine Bauch”, “Patricia Lebsack”,
    “Chelsey Dietrich”, “Mrs. Dennis Schulist”, “Kurtis Weissnat”, 
    “Nicholas Runolfsdottir V”, “Glenna Reichert”, “Clementina DuBuque”
]



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads