In this lesson, you gave the club’s species lookups promise types, watched the checker catch a missing await in a total an AI assistant suggested, and looked up a day’s sightings all at once with Promise.all().
Key Points
- An async function’s return type is a promise.
countIfKnown()returns a sighting’s count, anumber, but an async function always returns a promise, so you annotate its return asPromise<number>. Thenumberis what the promise gives you once it fulfills. The checker could infer this type on its own, but writing it down tells callers what they get and has the checker hold the function’s body to it. awaitturns aPromise<number>back into anumber. It waits for the promise to fulfill and gives you what’s inside, so the checker knows the type on each side of everyawait.- A promise where the types need its value is a type error. The suggested
total += countIfKnown(sighting)adds a promise to a number, andnpm run checkreports it before anything runs: errorTS2365, “Operator ‘+=’ cannot be applied to types ‘number’ and ‘Promise‘“, followed by “Did you forget to use ‘await’?” Adding awaitbefore the call fixes it. - Node.js runs the unchecked file anyway. It doesn’t check types, so the helper’s version prints
Known birds: 0followed by[object Promise]four times. With a promise,+=turns both sides into text, so each promise gets glued on. Promise.all()keeps the element type.today.map(countIfKnown)is aPromise<number>[]. Read from the outside in, the[]comes last, so it’s an array of promises.Promise.all()turns it into onePromise<number[]>, a single promise that holds an array of numbers, and awaiting that gives anumber[], one count per sighting, in the same order.- The checker doesn’t catch every forgotten
await. A promise dropped into a template literal withoutawaitgets no error, and neither does a call whose promise you never use at all. A linter rule calledno-floating-promisescatches the unused ones.
Final Code
Here’s daytotal.ts at the end of the lesson, run with the species API started by npm run api. The Sighting type is cut down from what the app exports, and "Atlantic Pufin" is misspelled, so the API doesn’t know it. It answers an unknown name with a not-found status, so response.ok is false and the count is zero: