Get the Return Type from a Promise in TypeScript

In this article, we'll explore how to get the return type from a Promise in TypeScript, a valuable skill for any TypeScript developer.

The Awaited Type in TypeScript is a handy little feature that allows us to model the await keyword so that we can unwrap types from a Promise.

Let's work with a couple of examples so you can see it in action.

In this first example, we are using the Promise<string> type which would suggest we should get a string after the Promise has been resolved.

We can quickly get the resolved value with the new Awaited type.

// PromiseReturnedValue = string
type PromiseReturnedValue = Awaited<Promise<string>>;

Now, I found this very useful when I depended on someone else's library and needed types, and depending on the query I made, I got different types.

Or if we want to chain a ReturnType with the Awaited keyword, we can unwrap the promise.

function somePromise(a: string) {
  return Promise.resolve(a);
}

//  type SomePType = string
type SomePType = Awaited<ReturnType<typeof somePromise>>;

A real-world example with Supabase

The following example is a query made in Supabase: I grab some todos from my database and then join the profiles but rename the profiles key as user.

export const getTodos = async () => {
  const { data, error } = await supabase
    .from("todos")
    .select("*, user:profiles(*)");
  if (error) throw new Error("Error fetching streams.");
  return data;
};

Now, imagine you want to get the type from data without having access to a specific type.

This situation made me reach for Awaited since I had no idea how to extract the needed information (since the types were changing depending on the query).

To grab the data types, I chained Awaited and ReturnType.

// fully typed type from the function
type GetTodosReturnType = Awaited<ReturnType<typeof getTodos>>;

As you continue your journey in TypeScript development, apply these techniques and explore their benefits in your projects. By doing so, you'll enhance your understanding of asynchronous programming and enrich your TypeScript skills.

Don't forget to check out more articles on Codú, join our community, and participate in events to stay connected and informed!

TsPromisesTypeScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.