#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
- Create an interface
Post. - Write an
asyncfunctiongetPosts()that simulates fetching data (usingsetTimeout). - It should return
Promise<Post[]>. - Call it and log the result using
await.
See you on Day 25 for Modules!