Typing async code and API responses
Course contents (16 lessons)
- Getting started
- Why TypeScript? What it is and what it is not
- Setting up TypeScript: tsc and tsconfig.json
- Core types
- Basic types: primitives, arrays, tuples, any and unknown
- Typing functions: parameters, returns, optionals and overloads
- Objects, interfaces and type aliases
- Unions, literals and enums
- Union types and type narrowing
- Literal types, enums and as const
- Classes and generics
- Classes in TypeScript
- Generics: writing reusable typed code
- Built-in utility types: Partial, Pick, Omit, Record and more
- Advanced types
- Mapped and conditional types
- Modules, type imports and declaration files
- TypeScript in real projects
- Typing async code and API responses
- Strict mode and compiler flags that matter
- Migrating a JavaScript project to TypeScript
- Final project: a type-safe task manager
Promises have a type
A promise holds a value of some type that arrives later. TypeScript writes this as Promise<T>. An async function always returns a promise, so its return type is Promise<...>, whether or not you write it.
interface User {
id: number;
name: string;
}
function wait(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function loadUser(id: number): Promise<User> {
await wait(50);
return { id, name: `User ${id}` };
}
async function main(): Promise<void> {
const user = await loadUser(1); // user is User
console.log(user.name);
const users = await Promise.all([loadUser(2), loadUser(3)]); // User[]
console.log(users.map(u => u.name));
}
main();
await unwraps the promise type, so await loadUser(1) has the type User. Promise.all keeps the order and types of each input, and gives you a tuple when you pass a fixed list.
A promise that resolves with nothing is Promise<void>. If you return a value from an async function that is declared Promise<User>, TypeScript checks that the value is a User.
The fetch problem
The built-in fetch is typed, but response.json() returns Promise<any>. In other words, TypeScript has no idea what the server sent. Many tutorials do this:
interface Post {
id: number;
title: string;
}
async function getPost(id: number): Promise<Post> {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
return response.json(); // any is silently accepted as Post
}
It compiles, and it looks safe, but it is a lie. The type Post is an assumption, since nothing checks it. If the API changes, or returns an error object, your code carries on with wrong data, and the crash appears later, far from the cause. This is the single most important thing to understand about TypeScript and external data: types are erased at runtime, so they cannot validate anything.
Step 1: check the response status
async function getJson(url: string): Promise<unknown> {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status} for ${url}`);
}
return response.json();
}
We return Promise<unknown>. The honest type for "data from outside" is unknown, which forces the caller to check it before use.
Step 2: validate with a type guard
A type guard, from the narrowing lesson, turns unknown into a real type, after really checking the data:
interface Post {
id: number;
title: string;
userId: number;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function isPost(value: unknown): value is Post {
return (
isRecord(value) &&
typeof value.id === "number" &&
typeof value.title === "string" &&
typeof value.userId === "number"
);
}
// a stand-in for a network call, so this example runs offline
async function fakeFetchJson(): Promise<unknown> {
return JSON.parse('{"id": 1, "title": "Hello", "userId": 7}');
}
async function getPost(): Promise<Post> {
const data = await fakeFetchJson();
if (!isPost(data)) {
throw new Error("The server returned data that is not a Post");
}
return data; // narrowed to Post
}
getPost().then(post => console.log(post.title.toUpperCase()));
Now if the API sends something unexpected, you get a clear error at the boundary, right where it entered your program. Everything after that point can trust the type.
Validating arrays and nested data
For lists, check every item:
interface Tag { id: number; name: string }
function isTag(value: unknown): value is Tag {
return (
typeof value === "object" && value !== null &&
typeof (value as Record<string, unknown>).id === "number" &&
typeof (value as Record<string, unknown>).name === "string"
);
}
function isTagList(value: unknown): value is Tag[] {
return Array.isArray(value) && value.every(isTag);
}
console.log(isTagList([{ id: 1, name: "a" }]), isTagList([{ id: "x" }]));
Hand-written guards get long for big payloads. That is when a validation library is worth adding. Libraries such as Zod, Valibot and ArkType let you describe the shape once, and give you both the runtime check and the TypeScript type from the same definition. I use them whenever an API has more than a handful of fields. The idea is the same as the guards above, with less typing.
A generic fetch helper
You can make the validation reusable by passing the guard in:
async function fetchJson<T>(
url: string,
guard: (value: unknown) => value is T,
): Promise<T> {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data: unknown = await response.json();
if (!guard(data)) throw new Error(`Unexpected response shape from ${url}`);
return data;
}
// usage
// const post = await fetchJson("https://example.com/posts/1", isPost);
The type T flows from the guard to the result, so post has the type Post and it was really checked.
A Result type instead of exceptions
Exceptions are invisible in a function signature. A caller cannot tell from the types that a function may fail. A simple alternative is to return a discriminated union that says whether it worked:
type Result<T> =
| { ok: true; value: T }
| { ok: false; error: string };
function parseAge(input: string): Result<number> {
const age = Number(input);
if (!Number.isInteger(age) || age < 0 || age > 120) {
return { ok: false, error: `"${input}" is not a valid age` };
}
return { ok: true, value: age };
}
for (const text of ["28", "abc", "200"]) {
const result = parseAge(text);
if (result.ok) {
console.log("Age:", result.value); // value only exists here
} else {
console.log("Error:", result.error); // error only exists here
}
}
The compiler will not let you read result.value before you check result.ok, so the failure case cannot be forgotten. I like this for expected failures such as validation. For truly unexpected ones, throwing is still fine.
Typing errors in catch
Under strict, the variable in a catch block is unknown, because anything can be thrown:
async function safeRun(task: () => Promise<void>): Promise<void> {
try {
await task();
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.log("Failed:", message);
}
}
safeRun(async () => { throw new Error("boom"); });
Common mistakes
- **Returning
response.json()as a typed value without checking.** It isany, so the type is a guess. - **Casting with
as Post.** It silences the compiler and checks nothing. - **Forgetting
await.** The variable is aPromise<T>, and property access will not compile. That is the compiler helping you. - **Typing a function as
Promise<any>.** UsePromise<unknown>or the real type. - **Ignoring
response.ok.** A 404 body is not your data. - Copying the API's whole payload into one giant interface. Type only the fields you use, and validate those.
Try it yourself
- Write a guard
isUserfor{ id: number; name: string; email: string }and test it with good and bad data. - Write
getJsonArray<T>(url, guard)that checks that the response is an array and that every item passes the guard. - Add a
Result<T>return type toparseAge-style functions forparseEmailandparseUrl. - Use
Promise.allSettledwith two typed promises and write code that handlesfulfilledandrejectedresults in a type-safe way.
interface User {
id: number;
name: string;
}
function wait(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function loadUser(id: number): Promise<User> {
await wait(50);
return { id, name: `User ${id}` };
}
async function main(): Promise<void> {
const user = await loadUser(1); // user is User
console.log(user.name);
const users = await Promise.all([loadUser(2), loadUser(3)]); // User[]
console.log(users.map(u => u.name));
}
main();
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account