In the overview, you saw the Millbrook Birders’ year list with “undefined” on it, put there by an import script that passed its type check without a single complaint. That script talks to the outside world twice: it reads the members’ app export, and it asks a species API about each bird. The checker never sees either answer, because by the time the data arrives, the types are gone.
In this lesson, you’ll start the club’s project, write a species lookup the way the old script did, and watch a type assertion wave a bad reply through. You’ll come away able to tell an assertion that’s justified from one that hides a bug.
Look Up a Species With as
To reproduce the club’s bug, you need a project to check code in and an API to ask about birds. The course’s Sample Code (.zip) download, linked on the course page and in the course introduction, has both in the Millbrook project, which you’ll add code to in every lesson. The course assumes you can write type annotations, union types, and narrowing checks. It also assumes you know why unknown is safer than any and can call fetch() with await.
You need a current Node.js release with long-term support (LTS), because Node.js runs .ts files from version 22.18 on. Check yours in a terminal:
$ node --version
v26.13.1
Your version number may differ. If it’s older than 22.18, then update Node.js to the current LTS first. Then download the Sample Code, extract it, and in a terminal, move into the extracted millbrook-birders folder and install its dependencies with npm:
$ cd millbrook-birders
$ npm install
That installs TypeScript, which gives you tsc, the TypeScript checker.
The project’s package.json has two scripts you’ll use. The "check" script, tsc --noEmit, checks every .ts file in the folder and writes nothing. Its tsconfig.json sets "strict": true, so the checking is strict from the first line you write. You’ll check with npm run check and run with node, two separate steps, because Node.js runs a .ts file without checking it.
The other script, "api", starts server.mjs, a small local stand-in for the public species API, so every output in this course is real. It knows five species. It answers a name it knows with the bird’s common name, scientific name, and conservation status, and any other name with an object holding an error message, as many real APIs do. It’s plain JavaScript, so npm run check doesn’t read it, and you won’t edit it. Start it:
$ npm run api
> [email protected] api
> node server.mjs
Species API running at http://localhost:3000
The server keeps running and holds on to this terminal. Open a second terminal, move into the millbrook-birders folder, and run the rest of this lesson’s commands there. Later lessons that call the API start it the same way. When you’re done for the day, go back to the server’s terminal and press Ctrl+C to stop it.
With the API running, you can write the lookup. The import script needs each reply’s names and status, but the checker can’t tell what the API will send. The .json() method of a fetch() response returns a promise of any, and any switches checking off, so a typo such as species.comonName would pass without a word.
The old script’s answer was a type assertion: value as Type tells the checker to treat a value as that type from now on. Create lookup.ts with the lookup written the same way:
lookup.ts
1type SpeciesResponse = {
2 commonName: string;
3 scientificName: string;
4 status: string;
5};
6
7const name = "Atlantic Puffin";
8const response = await fetch(
9 `http://localhost:3000/species?name=${encodeURIComponent(name)}`,
10);
11const species = (await response.json()) as SpeciesResponse;
12
13console.log(`${species.commonName} (${species.scientificName})`);
14console.log(`Status: ${species.status}`);
The SpeciesResponse type describes the reply for a known bird. On lines 8 to 10, encodeURIComponent() turns the space in the name into %20 so it can go in the address, and fetch() sends the request. On line 11, .json() reads the reply’s body as JSON, and the parentheses make as SpeciesResponse apply to the awaited value. From there on, the checker treats species as a SpeciesResponse and would catch that comonName typo. Run the lookup:
$ node lookup.ts
Atlantic Puffin (Fratercula arctica)
Status: Vulnerable
The reply matches the type, so the output is right. Members type species names into the app themselves, though, and slips happen. Change the name on line 7 to a misspelling someone in a hurry might type:
lookup.ts
1type SpeciesResponse = {
2 commonName: string;
3 scientificName: string;
4 status: string;
5};
6
7const name = "Atlantic Pufin";
8const response = await fetch(
9 `http://localhost:3000/species?name=${encodeURIComponent(name)}`,
10);
11const species = (await response.json()) as SpeciesResponse;
12
13console.log(`${species.commonName} (${species.scientificName})`);
14console.log(`Status: ${species.status}`);
Run the check first, as you would before trusting a change. It finds nothing wrong:
$ npm run check
> [email protected] check
> tsc --noEmit
The API doesn’t know a bird called “Atlantic Pufin”. Before you run the lookup, predict what it prints. Will the checker’s silence mean the script stops, warns you, or carries on?
The script carries on and prints “undefined” three times:
$ node lookup.ts
undefined (undefined)
Status: undefined
The API answered with {"error":"Unknown species: Atlantic Pufin"}. The assertion told the checker that the reply was a SpeciesResponse, and the checker took your word for it. An assertion is a claim that the checker accepts without verifying it.
At runtime, the error object has no commonName property, so reading it gives undefined, and the template literal turns that into the text "undefined". That’s how the club’s year list got its “undefined” entry.
See Why the Checker Let It Through
The checker passed a lookup that printed undefined, so you need to know what it actually checked and what happened to the assertion afterward. Start with the run. Before Node.js runs a .ts file, it replaces every type with blank space. Here are lines 7 to 14 of lookup.ts as Node.js runs them, with the blank space squeezed out:
const name = "Atlantic Pufin";
const response = await fetch(
`http://localhost:3000/species?name=${encodeURIComponent(name)}`,
);
const species = (await response.json());
console.log(`${species.commonName} (${species.scientificName})`);
console.log(`Status: ${species.status}`);
The as SpeciesResponse is gone, and so is the type it named. Nothing in the running program compares the reply with SpeciesResponse, because by then that type no longer exists.
The checker doesn’t accept every assertion you write, though. It compares the two types it knows and rejects the assertion when neither type fits the other, which the error message describes as insufficient overlap. Here’s a scratch file, overlap.ts, with two assertions side by side. Line 8 asserts the API’s error reply, written out as an object, and line 9 asserts an empty object:
overlap.ts
1type SpeciesResponse = {
2 commonName: string;
3 scientificName: string;
4 status: string;
5};
6
7const notFound = { error: "Unknown species: Atlantic Pufin" };
8const fromError = notFound as SpeciesResponse;
9const empty = {} as SpeciesResponse;
When you check the file with npm run check, you get one error, on line 8:
overlap.ts:8:19 - error TS2352: Conversion of type '{ error: string; }' to type
'SpeciesResponse' may be a mistake because neither type sufficiently overlaps
with the other. If this was intentional, convert the expression to 'unknown'
first.
Type '{ error: string; }' is missing the following properties from type
'SpeciesResponse': commonName, scientificName, status
8 const fromError = notFound as SpeciesResponse;
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Read the message from the top. The checker knows the type of notFound, { error: string; }. That type lacks all three properties a SpeciesResponse needs, and a SpeciesResponse doesn’t promise an error, so neither type fits the other and the checker flags the assertion as a likely mistake.
The checker judges the types and doesn’t rule out every possible value. Object types allow extra properties, so an object with error and the three species properties would fit both. The message ends by suggesting you convert to unknown first. That would silence the checker without fixing anything, so treat the error as a sign that the assertion is wrong.
Line 9 passes. Every SpeciesResponse is also an object, and an empty object type asks for no properties at all, so the two types overlap. At runtime, empty.commonName is undefined, as the lookup’s names were. If you then called empty.commonName.toUpperCase(), the program would stop with TypeError: Cannot read properties of undefined (reading 'toUpperCase').
The type error on line 8 wouldn’t stop Node.js from running the file either. Node.js removes as SpeciesResponse, and line 8 copies notFound into fromError.
The overlap rule never had a say in the lookup. Awaiting .json() yields any, and the checker lets any become every type, so as SpeciesResponse on the reply passes whatever the API sends. An annotation behaves differently on a value the checker can see: const empty: SpeciesResponse = {}; gets error TS2739, listing the three missing properties. On the lookup’s any, though, an annotation would pass too.
If the overlap rule still feels slippery, the button below opens a chat with the mentor, with this question filled in for you to send and this section attached. Ask it to walk through both assertions in overlap.ts one step at a time:
Save as for What’s Already Checked
An assertion is justified when something other than the assertion guarantees the type, and you can point to that guarantee. For an API’s reply, that something has to be a check in your own code, because the reply comes from outside your program.
Here’s that idea in outline. Replace lookup.ts with this version, which keeps the reply as unknown and checks it before trusting it:
lookup.ts
1type SpeciesResponse = {
2 commonName: string;
3 scientificName: string;
4 status: string;
5};
6
7const name = "Atlantic Pufin";
8const response = await fetch(
9 `http://localhost:3000/species?name=${encodeURIComponent(name)}`,
10);
11const reply: unknown = await response.json();
12
13if (
14 typeof reply === "object" && reply !== null &&
15 "commonName" in reply && typeof reply.commonName === "string" &&
16 "scientificName" in reply &&
17 typeof reply.scientificName === "string" &&
18 "status" in reply && typeof reply.status === "string"
19) {
20 const species = reply as SpeciesResponse;
21 console.log(`${species.commonName} (${species.scientificName})`);
22} else {
23 console.log(`No species found for "${name}"`);
24}
The annotation on line 11 means the checker won’t let you use reply until you’ve narrowed it. The condition on lines 14 to 18 uses typeof and in checks to rule out everything but an object with three string properties.
Inside the branch, reading a property such as reply.commonName gives a string, but reply itself still has unknown properties, so the checker won’t accept it as a SpeciesResponse without the assertion on line 20. That assertion says what lines 14 to 18 have already proved. The checker doesn’t compare the condition with the type, though, so if SpeciesResponse gains a property, update the check too. Run it with the misspelled name:
$ node lookup.ts
No species found for "Atlantic Pufin"
The bad reply now lands in the else branch instead of on the year list. That condition is long for three properties, and a whole sighting has more. A later lesson wraps a check like this in a function you can reuse, so that’s all you need about writing the checks for now.
The rule for justifying assertions applies elsewhere. In browser code, you’ll see document.querySelector("#year-list") as HTMLOListElement, which is reasonable when the page’s own HTML guarantees that an <ol id="year-list"> exists when the query runs. An assertion on data from a file, an API, or a user, without a check beforehand, can repeat the club’s bug.
You’ll also meet as const, which looks similar but isn’t this kind of assertion: it asks the checker to keep a value’s narrowest literal types rather than claiming a type for it.
When you find an as in code you’re reading, look for what guarantees it. If you’d like practice judging real ones, open a chat with the mentor and paste in an assertion from your own code or a package you use:
Check Your Understanding
Try these before you open the answers. They use the code from this lesson.
- A club member says, “
npm run checkpassed withas SpeciesResponsein the lookup, so the API’s reply must have the right shape.” What would you tell them? - Why does
{} as SpeciesResponsepass the check, while asserting{ error: "Unknown species" }as aSpeciesResponsefails withTS2352? - Which of these two assertions is justified, and why: the
as SpeciesResponseon line 11 of the firstlookup.ts, or the one on line 20 of the last version?
- The check only shows that the code agrees with the claim. An assertion tells the checker what type a value has, and the checker accepts it without looking at the value. The types are removed before the script runs, so nothing compares the reply with
SpeciesResponse. A misspelled name gets an error object, and the script printsundefined. - The checker allows an assertion between types that overlap. An empty object type asks for no properties, so every
SpeciesResponsefits it, and the types overlap. The error object’s type has none of the properties aSpeciesResponseneeds, and aSpeciesResponsedoesn’t promise anerror, so neither type fits the other, and the checker reports the assertion as a likely mistake. - The one on line 20 is justified. The condition before it checks that the reply is an object with three string properties, so the assertion says what the code already guarantees. The one on line 11 asserts the API’s reply without a check beforehand, which is how a lookup for “Atlantic Pufin” printed
undefined.
An assertion claims a type without checking it, so it belongs only where something else already guarantees that type. In the next lesson, Checking a Value With satisfies, you’ll put a type on the club’s import settings in three ways and see which one catches a typo while keeping the values’ precise types.