Lesson 9 / 28
Async Functions & Promise Types
Type asynchronous code with Promise<T> and async/await, and handle errors safely under strict mode.
An async function always returns a Promise. Declare the resolved type inside Promise<T>.
interface User { id: number; name: string }
async function fetchUser(id: number): Promise<User> {
const res = await fetch(`/api/users/${id}`);
return (await res.json()) as User;
}
const user = await fetchUser(1); // user: UserPromise.all keeps a type per position, and try/catch errors are unknown under strict mode, so narrow them.
const [a, b] = await Promise.all([fetchUser(1), Promise.resolve("ok")]);
// a: User, b: string
try {
await fetchUser(2);
} catch (e) {
if (e instanceof Error) console.log(e.message);
}Quick check
Quick check: What is the return type of `async function f(): Promise<number>`?
- number
- Promise<number>
- void
- unknown
Answer
Promise<number> — An async function always wraps its result in a Promise.