Menu

Async Code, Errors, and Typed APIs

Lesson 4: Async Code, Errors, and Typed APIs

How are async values typed?

Code Type
async function f(): Promise<Order> Resolves to Order
await f() Order
Promise.all([getCart(), getUser()]) Promise<[Cart, User]> (a typed tuple)
Promise.allSettled([...]) Array of fulfilled or rejected results
catch (error) unknown

Example

import { z } from 'zod';

class ApiError extends Error {
  constructor(message: string, public readonly status: number) {
    super(message);
    this.name = 'ApiError';
  }
}

async function apiGet<T>(path: string, schema: z.ZodType<T>): Promise<T> {
  const res = await fetch(`https://api.quickcart.in${path}`);
  if (!res.ok) throw new ApiError(`GET ${path} failed`, res.status);
  return schema.parse(await res.json());
}

const ProductSchema = z.object({ id: z.string(), name: z.string(), price: z.number() });
const CartSchema = z.object({ items: z.array(z.object({ productId: z.string(), quantity: z.number() })) });

async function loadCheckout(customerId: string) {
  const [cart, featured] = await Promise.all([
    apiGet(`/carts/${customerId}`, CartSchema),
    apiGet('/products/featured', z.array(ProductSchema)),
  ]);
  return { cart, featured }; // Both fully typed
}

async function main() {
  try {
    const checkout = await loadCheckout('c7');
    console.log(checkout.cart.items.length);
  } catch (error) {
    if (error instanceof ApiError && error.status === 404) {
      console.log('Cart not found');
    } else if (error instanceof Error) {
      console.error(error.message);
    } else {
      console.error('Unknown error', error);
    }
  }
}

How it works

  • Promise.all with an array literal infers a tuple, so each result keeps its own type.
  • apiGet<T> takes a schema, so the return type comes from validation, not from an unchecked as.
  • catch (error) is unknown because JavaScript can throw anything. Narrow with instanceof before reading properties.
  • Custom error classes carry extra data, such as an HTTP status, in a typed way.

Common mistakes

Mistake Effect Fix
catch (e: any) { e.message } Crashes if a non-Error is thrown Narrow unknown with instanceof Error
Forgetting await You pass a Promise where a value is expected (usually a type error) Enable the no-floating-promises lint rule
res.json() as Product Unchecked data trusted Parse with a schema

Key takeaways

  • Async functions return Promise<T>; Promise.all keeps each result's type.
  • Treat caught errors as unknown and validate API data with schemas.

Try it: Write placeOrder(input: CreateOrderInput): Promise<Result<Order, ApiError>> that never throws and returns a typed failure for non-OK responses.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details