#typescript #async #promises

Day 24: Async/Await and Promises

The Async World

Welcome to Phase 5! Apps deal with APIs, databases, and timers. That means Async.

Typing Promises

A Promise is generic. It returns a Promise<T>.

const myPromise: Promise<string> = new Promise((resolve) => {
  resolve("Hello");
});

Async/Await

When you use async, the return type is always a Promise.

interface User {
  id: number;
  name: string;
}

async function fetchUser(id: number): Promise<User> {
  const res = await fetch(\`https://api.example.com/users/\${id}\`);
  const data = await res.json();
  return data; // TypeScript ensures this matches User
}

Awaited Utility

If you have a Promise type and want to know whatโ€™s inside it, use Awaited.

type UserResponse = ReturnType<typeof fetchUser>; // Promise<User>
type UserData = Awaited<UserResponse>; // User

Challenge for Today

  1. Create an interface Post.
  2. Write an async function getPosts() that simulates fetching data (using setTimeout).
  3. It should return Promise<Post[]>.
  4. Call it and log the result using await.

See you on Day 25 for Modules!