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
typeofcheck narrows that property, not the object. After thetypeofandinchecks,entry.speciesreads as astringinside the branch, butentryisobject & Record<"species", unknown> & ...to the checker. EachRecordpart says the object has one property, likespecies, ofunknowntype. So passingentrytoyearListLine(sighting: Sighting)gets errorTS2345:Types of property 'species' are incompatible. - A type predicate says what
truemeans.function isSighting(value: unknown): value is Sightingstill returnstrueorfalseat runtime. Thevalueinvalue is Sightingis the parameter’s name, so the claim is about whatever you pass in. The return typevalue is Sightingis a type predicate, and a function with one is a type guard. - The checker narrows inside the branch. In
if (isSighting(entry)), hovering overentryin the condition showsunknown, and inside the branch it showsSighting, so theyearListLine(entry)call that the checker rejected before now passes. With a plainbooleanreturn type,entrywould stayunknownin the branch. - A renamed field gets rejected. An entry from the app update that calls the species field
commonNamefails the guard, so the import printsRejected: not a sightinginstead 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 asundefined. 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:
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:
$ 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.