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.