In this lesson, you watched an annotation let the renamed-field export through to the year list, saw why, and found the three places where data enters the club’s import: the export, the species API’s reply, and an environment variable for the API’s address.
Key Points
- An annotation on outside data checks nothing. The old script asserted the export’s type with
as. An annotation looks like the safer replacement, since one caught the typo in the settings. But with the species field renamed tocommonName,const sightings: Sighting[] = JSON.parse(text);passesnpm run checkwith no errors, and the loop putsundefinedon the year list. JSON.parse()returnsany. Its hover ends in: any, andanyswitches checking off, so the checker accepts the result as an array of sightings, or as whatever type you write.- The types are gone when the data arrives. Node.js strips the types before it runs the file, so line 4 runs as
const sightings = JSON.parse(text);. The checker reads your code before it runs, and the export’s data arrives only while the program runs, with no type left to compare it with. unknownkeeps the checker on guard. Withconst sightings: unknown = JSON.parse(text);, the check reports errorTS18046, “‘sightings’ is of type ‘unknown’”, at the loop. That’s the error you want, because the loop can’t pass the check until something checks the export.unknownis erased too, so Node still runs the file and printsYear list: undefined.- A boundary is a place where data comes in from outside the program. To spot one, ask whether a value comes from something your code didn’t write, such as a file, the network or the environment. A value that arrives as
anyis often the sign. The import has three:- The export. Its text arrives as a plain string, and
JSON.parse()is where it turns into data of any shape, so that’s where it getsunknown. - The species API’s reply.
response.json()returnsPromise<any>, so the awaited reply has typeany, like the valueJSON.parse()returns. You typed it asunknownin the first lesson, because that’s where the reply enters. - The API’s address, read from an environment variable with
process.env.SPECIES_API. Its type isstring | undefined, an honest type. Node gives an environment variable as text or leaves it unset, and the type claims no more than that. It says nothing about what the text holds, so the check has to confirm that it’s there and that it’s a URL.
- The export. Its text arrives as a plain string, and
- Reading
process.envneeds Node’s types.processbelongs to Node.js, not to JavaScript, so the check reports errorTS2591, “Cannot find name ‘process’”, until you take both steps the message names. Install@types/nodeas a dev dependency, then add"types": ["node"]tocompilerOptionsintsconfig.json, because current TypeScript doesn’t pick up installed type packages on its own.
Final Code
Install Node’s types in the millbrook-birders folder: