Loading video player…

Writing Your Own Type Guards

In this lesson, you wrapped the club’s long sighting check in a function, isSighting(), whose return type tells the checker what a true result means, so an unknown entry from the export becomes a Sighting inside the branch that calls it.

Key Points

  • A property’s typeof check narrows that property, not the object. After the typeof and in checks, entry.species reads as a string inside the branch, but entry is object & Record<"species", unknown> & ... to the checker. Each Record part says the object has one property, like species, of unknown type. So passing entry to yearListLine(sighting: Sighting) gets error TS2345: Types of property 'species' are incompatible.
  • A type predicate says what true means. function isSighting(value: unknown): value is Sighting still returns true or false at runtime. The value in value is Sighting is the parameter’s name, so the claim is about whatever you pass in. The return type value is Sighting is a type predicate, and a function with one is a type guard.
  • The checker narrows inside the branch. In if (isSighting(entry)), hovering over entry in the condition shows unknown, and inside the branch it shows Sighting, so the yearListLine(entry) call that the checker rejected before now passes. With a plain boolean return type, entry would stay unknown in the branch.
  • A renamed field gets rejected. An entry from the app update that calls the species field commonName fails the guard, so the import prints Rejected: not a sighting instead of adding it to the year list.
  • The checker trusts the predicate. It doesn’t verify that the body’s checks back up the return type. A guard that only checks for an object still passes npm run check, and the renamed entry goes on the year list as undefined. Check every property the type promises.

Final Code

Here’s sightings.ts at the end of the lesson. The Sighting type is cut down to three of the five properties the club’s app exports. isSighting() checks each of them, and addToYearList() takes an entry from the export as unknown and only builds a year-list line once the guard returns true:

Language: TypeScript Filename: sightings.ts
type Sighting = {
  species: string;
  count: number;
  site: string;
};

function isSighting(value: unknown): value is Sighting {
  return (
    typeof value === "object" && value !== null &&
    "species" in value && typeof value.species === "string" &&
    "count" in value && typeof value.count === "number" &&
    "site" in value && typeof value.site === "string"
  );
}

function yearListLine(sighting: Sighting) {
  return `${sighting.species}: ${sighting.count} at ${sighting.site}`;
}

function addToYearList(entry: unknown) {
  if (isSighting(entry)) {
    console.log(yearListLine(entry));
  } else {
    console.log("Rejected: not a sighting");
  }
}

const kite = '{"species":"Red Kite","count":2,"site":"Gull Point"}';
const egret = '{"commonName":"Little Egret","count":1,"site":"Gull Point"}';
addToYearList(JSON.parse(kite));
addToYearList(JSON.parse(egret));

The check is clean, and Node.js adds the red kite to the year list and rejects the entry with the renamed field:

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit

$ node sightings.ts
Red Kite: 2 at Gull Point
Rejected: not a sighting

isSighting() tells you whether an entry is a sighting. In the next lesson, Guarding With Assertion Functions, you’ll decide what should happen when the check fails and the program can’t go on.

00:00 In the last exercise, you replaced the old import script’s assertions with typeof checks. For a whole sighting, those checks get long. Here’s a sighting type, cut down to three of the five properties the club’s app exports: the species, the count, and the site.

00:17 The yearListLine function turns a sighting into a line for the year list. The addToYearList function takes one entry from the export as unknown. Its condition checks each property before the entry is used.

00:31 Run the check, and the checker rejects the yearListLine call. Read the error from the top. To the checker, entry is an object whose species, count and site have unknown types.

00:43 Each Record part says the object has one property, like species, of unknown type.

00:50 Each typeof check narrowed a property where you read it. Inside the branch, entry.species reads as a string. But the type of entry itself, the value you pass to yearListLine, keeps those unknowns.

01:03 So the condition is long, and it still doesn’t turn entry into a sighting.

01:09 Move the condition into a function of its own. isSighting takes an unknown value. Inside, entry becomes value, and the function returns the same checks. Look at its return type.

01:22 Where you might expect boolean, value is Sighting tells the checker more. The word value here is the parameter’s name, so the claim is about whatever you pass in.

01:33 The function still returns true or false when it runs. The return type tells the checker what a true result means. Here, it means the value you passed in is a sighting.

01:44 The if statement in addToYearList now calls isSighting with the entry.

01:51 Hover over entry in the condition, and it’s unknown, the type addToYearList gave it. Hover over it inside the branch, and the checker treats it as a sighting.

02:02 When isSighting returns true, the checker narrows entry to the type that the return type names. A return type like this is a type predicate, and a function with one is a type guard.

02:14 Run the check, and it’s clean. The call to yearListLine that the checker rejected before passes now. A plain boolean return type wouldn’t do this. The checker would see only true or false, and entry would stay unknown in the branch.

02:31 Now add a second entry. After last spring’s app update, the export calls the species field commonName instead. Run the file. The red kite goes on the year list, and the egret is rejected.

02:45 Watch out, though. The checker doesn’t verify that the body’s checks back up the return type. It trusts the predicate. Cut the body down to the object check alone.

02:56 The check is still clean. Run the file, and the egret goes on the year list as undefined, the club’s bug again. So when you write a guard, check every property the type promises.

03:09 Put the full checks back.

03:12 A function whose return type says the value is a sighting is a type guard. When it returns true, the checker narrows the value to that type inside the branch.

03:23 The checker trusts the guard, so make it check every property the type promises.

03:29 isSighting tells you whether an entry is a sighting. But what should happen when the check fails and the program can’t go on? The lesson Guarding With Assertion Functions answers that next.

Become a Member to join the conversation.