⭐ 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;
};
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;
};
Same as before, these can be extracted into their own types as well:
type GetUser = (id: string) => Promise<User>;
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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
Top comments (0)