Typed async code in TypeScript
Promise return types and asserting fetched shapes.
interface Repo {
name: string;
stars: number;
}
async function fetchRepos(user: string): Promise<Repo[]> {
const response = await fetch(`/api/users/${user}/repos`);
if (!response.ok) throw new Error(`status ${response.status}`);
return (await response.json()) as Repo[];
}
async function total(user: string): Promise<number> {
const repos = await fetchRepos(user);
return repos.reduce((sum, repo) => sum + repo.stars, 0);
}
How it works
Promise<Repo[]>types what the function resolves to.as Repo[]asserts the shape of parsed JSON.reducestays type-safe over the typed array.
Keywords and builtins used here
Promiseasasyncawaitconstfunctionifinterfacenumberreturnstringthrow
The run, in numbers
- Lines
- 15
- Characters to type
- 425
- Tokens
- 123
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 70 seconds.
Step 1 of 2 in Async types, step 1 of 8 in Async & modules.