Type async code and APIs

INPUT · Slides

Receive with unknown, narrow to use

01 / 03

Data from outside could be anything

Parse JSON from a server and the result could be an object, a string, or null.

TypeScript uses unknown for things whose type is not known yet. Unlike any, you cannot use it until you check.

const data: unknown = JSON.parse('{"name": "Yui"}');// data.name — error (unknown)

02 / 03

Narrow with typeof

typeof data === "string" tells TypeScript "inside here it is a string".

This is the same narrowing from chapter 3, applied to unknown.

function show(data: unknown): void {  if (typeof data === "string") {    console.log(data.toUpperCase());  } else {    console.log("not a string");  }}show("hello");

Result

HELLO

03 / 03

Checking for an object

API responses are usually objects. Check with typeof data === "object" && data !== null, then "name" in data to verify properties.

It feels like work, but it is much safer than data slipping through broken.

function getName(data: unknown): string {  if (    typeof data === "object" &&    data !== null &&    "name" in data  ) {    return String((data as Record<string, unknown>).name);  }  return "unknown";}console.log(getName({ name: "Yui" }));

Result

Yui