← Learning Hub
Intermediate

Async Code with Promise Types

An async function always returns a Promise. In TypeScript you write what the promise will hold: Promise<Product>.

Most real code waits for something - a server, a database, a file. TypeScript types what a promise will hold (Promise<Product>), so after await you get full type checking and editor help on the result.

Example
You can edit this code.

Running things at the same time

Example
You can edit this code.

Typing data from fetch

Example
interface Joke { id: number; setup: string; punchline: string }

async function getJoke(): Promise<Joke> {
  const res = await fetch("https://example.com/api/joke");
  if (!res.ok) throw new Error("HTTP " + res.status);
  return (await res.json()) as Joke;    // 'as' trusts the server - check important data
}
res.json() can't know the real shape. as Joke is a promise from you to TypeScript. For data you can't trust, check it (see the type guards lesson).
Key points
  • async functions return Promise<T>.
  • Caught errors are unknown - check them.
  • Promise.all runs tasks together and keeps types.

📝 Test yourself

1. What does an async function return?
2. In TypeScript's strict mode, what type is err in catch (err)?
3. Fill in the type for an async function that returns a number:
async function count(): <number> { return 5; }