DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

1

Beginner's TypeScript #18

Image description

Typing Async Functions

Let's go deeper into function types.

Here we have a createThenGetUser function:

const createThenGetUser = async (
  createUser: unknown,
  getUser: unknown,
): Promise<User> => {
  const userId: string = await createUser();

  const user = await getUser(userId);

  return user;
};
Enter fullscreen mode Exit fullscreen mode

This function takes in an asynchronous createUser function. It returns a promise that includes a userId string.

The userId string is then used in a call to getUser which would be a database call or something similar.

Both createUser and getUser are currently typed as unknown.

We will figure out how to type the async functions.

🌟 Solution: Specify the Type for an Async Function

Here is the correct syntax for typing these functions:

const createThenGetUser = async (
  createUser: () => Promise<string>,
  getUser: (id: string) => Promise<User>,
): Promise<User> => {
  const userId: string = await createUser();

  const user = await getUser(userId);

  return user;
};
Enter fullscreen mode Exit fullscreen mode

Same as before, these can be extracted into their own types as well:

type GetUser = (id: string) => Promise<User>;
Enter fullscreen mode Exit fullscreen mode

What this is saying is that we have an id which is a string, and the function will return a Promise containing a User.

If we had GetUser only returning the User without the Promise, we wouldn't be able to call it as an async function.

Wrapping function return types with Promises is really useful when working with real-world processes like fetching from databases.


I hope you found it useful. Thanks for reading. 🙏

Let's get connected! You can find me on:

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay