Checking Data Once at the Boundary

At the end of the last lesson, the club’s import had three boundaries, each typed where its data enters. The export is unknown, the species API’s reply is unknown, and the API’s address is string | undefined. npm run check still flagged the loop over the export, because nothing had checked it yet.

In this lesson, you’ll write those checks. You’ll turn the whole export into an array of sightings, item by item, and report the entries that fail. You’ll also check the address and each reply once, where they arrive, so the rest of the import can trust its types. Start with the export, where the check has to reach every entry.

Check Every Sighting in the Export

The loop over the export needs an array, and every entry in it has to be a sighting. To test that, the club put together a small export with both problems it has encountered: the renamed field from last spring and a count that Tomás typed as text. You’ll check it in a new file, check-export.ts, in your millbrook-birders folder.

That file takes over the export half of the last lesson’s boundaries.ts, and you’ll write its lookup half again later in this lesson. So delete boundaries.ts from the folder now. npm run check checks every .ts file in the project, and that file’s unchecked loop would keep failing.

The first test is whether the export is an array at all, with Array.isArray(). Array.isArray() narrows an unknown value to any[], so it vouches for the array and nothing in it. Each entry needs a check of its own, and for that you already have isSighting(), the type guard for the three-property Sighting type that you fixed in the exercise Guard the Sightings.

What’s new is the decision about failures. One bad entry shouldn’t sink an export of eight sightings, so a failing entry is rejected and reported, and the rest carry on. If the export isn’t an array at all, there’s nothing to import, so that case throws, as assertSettings() did for broken settings. Create check-export.ts:

Language: TypeScript Filename: check-export.ts
 1type Sighting = { species: string; count: number; site: string };
 2
 3function isSighting(value: unknown): value is Sighting {
 4  return (
 5    typeof value === "object" &&
 6    value !== null &&
 7    "species" in value &&
 8    typeof value.species === "string" &&
 9    "count" in value &&
10    typeof value.count === "number" &&
11    "site" in value &&
12    typeof value.site === "string"
13  );
14}
15
16function checkEntry(entry: unknown, index: number) {
17  if (isSighting(entry)) {
18    return entry;
19  }
20  console.log(`Rejected entry ${index + 1}: not a sighting`);
21  return undefined;
22}
23
24function readSightings(data: unknown): Sighting[] {
25  if (!Array.isArray(data)) {
26    throw new Error("The export must hold an array of sightings");
27  }
28  return data.map(checkEntry);
29}
30
31const text = `[
32  {"species":"Red Kite","count":2,"site":"Gull Point"},
33  {"commonName":"Little Egret","count":1,"site":"Gull Point"},
34  {"species":"Atlantic Puffin","count":"3","site":"Gull Point"}
35]`;
36const sightings = readSightings(JSON.parse(text));
37
38for (const sighting of sightings) {
39  console.log(`Year list: ${sighting.species}`);
40}

checkEntry() checks one entry. It returns the entry, narrowed to a Sighting, or reports it by position and returns undefined. readSightings() takes the parsed export as unknown, makes sure it’s an array, and runs every item through checkEntry() with .map(). Its return type, Sighting[], is the promise the rest of the import relies on. Check the project:

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit

check-export.ts:28:3 - error TS2322: Type '(Sighting | undefined)[]' is not
assignable to type 'Sighting[]'.
  Type 'Sighting | undefined' is not assignable to type 'Sighting'.
    Type 'undefined' is not assignable to type 'Sighting'.

28   return data.map(checkEntry);
     ~~~~~~

Found 1 error in check-export.ts:28

Read it from the top. readSightings() promised a Sighting[], but .map() built a (Sighting | undefined)[]. The last line explains the mismatch, since undefined isn’t a Sighting. checkEntry() returns undefined for each rejected entry, and .map() keeps those values in the array. Run the file, and the checker turns out to be right:

Language: Shell
$ node check-export.ts
Rejected entry 2: not a sighting
Rejected entry 3: not a sighting
Year list: Red Kite
...
TypeError: Cannot read properties of undefined (reading 'species')
...

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.