Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

Outside data and asynchronous code

By the end of this chapter, you'll be able to

  • Receive outside data with the unknown type
  • Write a type guard that checks a value at run time
  • Type asynchronous functions with Promise<T>
  • Handle an error of type unknown in a catch

unknown: “I don't know yet”

JSON.parse returns any: TypeScript then lets you do anything, even nonsense. The unknown type is its careful opposite: the value can be anything, so nothing is allowed until you have checked it.

const data: unknown = JSON.parse('{"name": "Mango", "price": 300}');
console.log(data.price);
TS18046: 'data' is of type 'unknown'.

To use the value, you must narrow it, as in the chapter on objects: typeof, in, Array.isArray…

const data: unknown = JSON.parse('{"name": "Mango", "price": 300}');

if (typeof data === "object" && data !== null && "price" in data && typeof data.price === "number") {
  console.log(data.price * 2);
}
600

Each test reduces the possibilities: an object, not null, that has a price property, which is a number. After these tests, data.price is a number.

Type guards

Repeating these tests everywhere would be tedious. We put them in a type guard: a function that returns a boolean and whose return type value is Product tells TypeScript what true means.

interface Product {
  name: string;
  price: number;
}

function isProduct(v: unknown): v is Product {
  return (
    typeof v === "object" && v !== null &&
    "name" in v && typeof v.name === "string" &&
    "price" in v && typeof v.price === "number" && v.price >= 0
  );
}

const inputs: unknown[] = JSON.parse('[{"name": "Mango", "price": 300}, {"name": "Pineapple"}, {"name": "Coconut", "price": -5}]');
const valid = inputs.filter(isProduct);
console.log(valid.map((p) => `${p.name}: ${p.price}`));
["Mango: 300"]

filter(isProduct) returns a Product[]: TypeScript understands the guard. The guard also checks business rules (price >= 0) that types alone cannot express. In large projects, libraries such as Zod generate these checks from a schema.

Only checked values enter the typed code.

Step 5 of 5
Text description of the animation
  1. The data comes from a place TypeScript does not control.
  2. It arrives as text.
  3. After JSON.parse, we declare it unknown: nothing is allowed without checking.
  4. The guard tests every field at run time. Here, the price is missing: the object is rejected.
  5. Only checked values enter the typed code.

Type asynchronous code

An async function always returns a promise. You write its return type Promise<T>, where T is the type of the value obtained with await. Here, loadText simulates a network call with a delay:

function loadText(url: string): Promise<string> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (url.endsWith("/products")) resolve('[{"name": "Millet", "price": 450}]');
      else reject(new Error(`404 on ${url}`));
    }, 50);
  });
}

async function loadProducts(url: string): Promise<string[]> {
  const text = await loadText(url);
  const data: unknown = JSON.parse(text);
  if (!Array.isArray(data)) throw new Error("unexpected response");
  return data.map((d) => String(d.name));
}

try {
  console.log(await loadProducts("/api/products"));
  await loadProducts("/api/customers");
} catch (e) {
  console.log(e instanceof Error ? e.message : "unknown error");
}
["Millet"]
404 on /api/customers

Two important details:

  • Array.isArray narrows data to an array… of any items: d.name is not checked. String(d.name) at least avoids a crash. In a real application, you would apply a guard to each item.
  • In a catch, the error e has type unknown in strict mode: anything can be thrown with throw. e instanceof Error narrows it before reading e.message.

Mini-lab: validate an orderTypeScript

Output

Click “Run”: the TypeScript compiler will be loaded in your browser (about 3 MB the first time). Your code is checked, then run if it has no type error.

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: reliable marks

An API returns pupils' marks in the format {"pupil": "…", "mark": …}. Write a guard isMark that only accepts whole marks between 0 and 20, then an async validAverage(text) function that parses the JSON, keeps the valid marks and returns their average rounded to one decimal place (or null if there are none).

Hint 1
Number.isInteger(v.mark) checks that a number is whole.
Hint 2
The return type is Promise<number | null>.
Show the solution and common mistakes
interface Mark {
  pupil: string;
  mark: number;
}

function isMark(v: unknown): v is Mark {
  return typeof v === "object" && v !== null &&
    "pupil" in v && typeof v.pupil === "string" &&
    "mark" in v && typeof v.mark === "number" &&
    Number.isInteger(v.mark) && v.mark >= 0 && v.mark <= 20;
}

async function validAverage(text: string): Promise<number | null> {
  const data: unknown = JSON.parse(text);
  const marks = Array.isArray(data) ? data.filter(isMark) : [];
  if (marks.length === 0) return null;
  const sum = marks.reduce((s, m) => s + m.mark, 0);
  return Math.round((sum / marks.length) * 10) / 10;
}

console.log(await validAverage('[{"pupil": "Ali", "mark": 14}, {"pupil": "Ama", "mark": 25}, {"pupil": "Ibou", "mark": 11}, {"pupil": "Ada", "mark": "15"}]'));
console.log(await validAverage("{}"));
12.5
null

The mark 25 (out of range) and the mark "15" (a string) are discarded. A JSON value that is not an array gives an empty list, hence null.

Common mistakes:

  • Forgetting v !== null: typeof null is "object", and the test "pupil" in v would crash on null.
  • Declaring the return type Promise<number>: the function can return null, and TypeScript refuses it (TS2322). This is a good thing: the caller knows it must handle this case.

Summary

  1. 1Outside data is declared unknown: nothing is allowed before checking.
  2. 2A type guard (v is Product) checks a value at run time and tells TypeScript the result.
  3. 3as asserts without checking: avoid it for data coming from outside.
  4. 4An async function returns Promise<T>, where T is the type obtained with await.
  5. 5In a catch, the error is unknown: narrow it with instanceof Error.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.