Sikau

TypeScript · Day 21 · about 30 min

Typing async code

Promise<T> and checking data from the internet.

Trust, but verify

Async functions return Promise<T>. But data from an API is the one place types can lie: response.json() gives any, and the server might send something else. The safe habit: treat outside data as unknown and check it with a type guard.

Promise types and type guards

async function wait(ms: number): Promise<void> {
  await new Promise((r) => setTimeout(r, ms));
}

async function getCount(): Promise<number> {
  await wait(10);
  return 42;
}

interface Quote {
  quote: string;
  author: string;
}

function isQuote(value: unknown): value is Quote {
  return (
    typeof value === "object" && value !== null &&
    typeof (value as Record<string, unknown>).quote === "string" &&
    typeof (value as Record<string, unknown>).author === "string"
  );
}

const data: unknown = JSON.parse('{"quote":"Little by little","author":"Proverb"}');
if (isQuote(data)) console.log(data.author);
getCount().then((n) => console.log(n + 1));

In real projects, schema libraries like Zod generate these checks (and the types) for you. The idea is the same.

The rest of this lesson

  • Promise types flow through awaitexplain
  • Validating outside dataexplain
  • What's the return type?predict
  • Async return typepredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of TypeScript