lecture 7 of 110 completed

Checking a response at run time

A type guard is code that looks at a value while the program runs. After it, the type is true because something checked it.

What you'll learn

  • How to check an unknown value step by step
  • What a type predicate tells the compiler, and why the guard needs its own tests
  • How to reject a bad response with a message that names the field

Four lectures in this track ended the same way.

  • Lecture 3: parse<Book>(text) compiled, and the field was undefined.
  • Lecture 4: the builder returned a Book with copies set to undefined.
  • Lecture 5: private was readable through as any.
  • Lecture 6: getLoan returned a Loan, and nothing had looked at the body.

Add the ones from the Junior track and the list is long. Each time, somebody told the compiler what a value is, and the compiler believed it.

For your own code that is usually fine, because the compiler works most types out. For data from outside the program it is never fine. A server, a file and a page do not read your types.

This lecture ends the list. You will write code that looks at the value.

Start from unknown

Give the parsed value the type unknown. The compiler then refuses every use until you have checked.

const value: unknown = JSON.parse('{"title":"Dune","copies":3}');
console.log(value.title);
books.ts(2,13): error TS18046: 'value' is of type 'unknown'.

Check one thing at a time

A book is an object with a title that is text and a copies that is a number. Check in that order: first the object, then each field.

interface Book {
  title: string;
  copies: number;
}

function isBook(value: unknown): value is Book {
  if (typeof value !== "object" || value === null) {
    return false;
  }
  if (!("title" in value) || typeof value.title !== "string") {
    return false;
  }
  if (!("copies" in value) || typeof value.copies !== "number") {
    return false;
  }
  return true;
}

console.log(isBook({ title: "Dune", copies: 3 }));
console.log(isBook({ title: "Dune", copyCount: 3 }));
console.log(isBook(null));
true
false
false

Walk through the three checks.

The first asks whether the value is an object. It needs two parts, because of an old rule of the language: typeof null is "object". Without value === null, a null body would pass.

The second asks whether the object has a title, and whether it is text. in narrows the value so that value.title may be read. This is the in check from lecture 1.

The third does the same for copies.

The type predicate

The return type is value is Book, where you would expect boolean. This is a type predicate. It tells the compiler: when this function returns true, treat the argument as a Book.

A function with a type predicate is called a type guard. Use it in an if, and the compiler narrows.

interface Book {
  title: string;
  copies: number;
}

function isBook(value: unknown): value is Book {
  if (typeof value !== "object" || value === null) {
    return false;
  }
  if (!("title" in value) || typeof value.title !== "string") {
    return false;
  }
  if (!("copies" in value) || typeof value.copies !== "number") {
    return false;
  }
  return true;
}

const body: unknown = JSON.parse('{"title":"Dune","copies":3}');
if (isBook(body)) {
  console.log(body.copies.toFixed(0));
}
3

Inside the if, body is a Book. This time the type is true, because code that ran made sure of it.

The last claim

The predicate is itself something you tell the compiler. It does not check that your function looks at the right fields.

interface Book {
  title: string;
  copies: number;
}

function isBook(value: unknown): value is Book {
  return true;
}

const body: unknown = JSON.parse('{"title":"Dune"}');
if (isBook(body)) {
  console.log(body.copies.toFixed(0));
}
TypeError: Cannot read properties of undefined (reading 'toFixed')

A guard that checks nothing compiles, and the code stops as before. The wording is from the engine in Node and Chrome.

The difference from every earlier claim is what kind of thing it is. as Book is one word with nothing behind it. A guard is a function. It runs, so you can test it: give it a good value, a value with a field missing, a value with a wrong type, and null. Those few tests are what make the predicate true. A guard with no tests is no better than as.

Reject with a reason

In a test, false is not much help. You want to know which field was wrong. So the usual form is a function that returns the checked value or throws.

interface Book {
  title: string;
  copies: number;
}

function parseBook(value: unknown): Book {
  if (typeof value !== "object" || value === null) {
    throw new Error("A book must be an object");
  }
  if (!("title" in value) || typeof value.title !== "string") {
    throw new Error("title must be text");
  }
  if (!("copies" in value) || typeof value.copies !== "number") {
    throw new Error("copies must be a number");
  }
  return { title: value.title, copies: value.copies };
}

console.log(parseBook(JSON.parse('{"title":"Dune","copies":3}')));
console.log(parseBook(JSON.parse('{"title":"Dune","copies":"3"}')));
{"title":"Dune","copies":3}
Error: copies must be a number

The second call stops with a message that names the field. Compare that with a test that fails ten lines later on undefined.

Put this at the edge, in the one function from lecture 6 that reads the response. After parseBook, every test holds a Book that was checked. The claim from lecture 6 is gone.

A list needs one more step. Array.isArray(value) checks for a list, and then you check each item.

Projects often use a schema library to write these checks in fewer lines. The idea underneath is the one in this lecture: code that runs looks at the value, and the type comes from that code.

Remember this

A type is true at run time only when code that runs has checked the value. Start from unknown, check the object and then each field, and throw an error that names the field. A type predicate is still a claim, so test the guard with good and bad values.

Reference: Using type predicates in the TypeScript Handbook.

now prove it

Reading is the setup. Solve this exercise in the editor. We check your code with the TypeScript compiler. Then we run it on each case and compare what it prints with the expected output.