Type async code and APIs

INPUT · Slides

Define a response type

01 / 03

Type the data from a server

Front-end code receives JSON from a server and puts it on screen. The JSON is an object like { id: 1, title: "Shopping", done: false }.

Declaring the shape first is how things are done in the real world. Misspell a property and you know immediately.

interface TodoItem {  id: number;  title: string;  done: boolean;}const item: TodoItem = { id: 1, title: "Shopping", done: false };console.log(item.title);

Result

Shopping

02 / 03

Arrays of typed objects

Data from a server usually comes as an array. Write TodoItem[] and for...of keeps the types.

interface TodoItem {  id: number;  title: string;  done: boolean;}const items: TodoItem[] = [  { id: 1, title: "Shopping", done: false },  { id: 2, title: "Cleaning", done: true },];for (const item of items) {  console.log(`${item.title}: ${item.done ? "done" : "not done"}`);}

Result

Shopping: not done
Cleaning: done

03 / 03

In practice, types live in their own file

Types are usually gathered in one file and imported with import type. The type definition serves as a spec for the data.