In this lesson, you read the old crossing’s optional delay safely, so a crossing with no report no longer shows as undefined min late and a delay of 0 shows as on time.
Key Points
- An optional property reads as a union with
undefined.const delay = crossing.delayMinutes;has the typenumber | undefined, so passing it tolateLine(minutes: number)getsArgument of type 'number | undefined' is not assignable to parameter of type 'number'.The checker is right. Without a check,node delays.tsprintsHL-1120: undefined min late. - The checker follows your checks. Inside
if (delay) { ... }, hovering overdelayshowsnumber. The checker followed your check into the branch and leftundefinedbehind. That’s narrowing, as you saw with atypeofcheck in Writing Union Types. - A truthiness check drops zero too. The checker accepts the call inside
if (delay). But0is falsy, so a crossing whose skipper reported a delay of0lands in the same branch as a missing report and showsHL-0940: no report yet. - Check what you mean.
if (delay !== undefined)lets only a missing delay fail the test, soHL-0940: 0 min lateshows. Atypeof delay === "number"check narrowsdelaytonumberthe same way. Both tests are plain JavaScript, so they stay in the file and still run after Node strips the types. - An early return narrows what comes after it. After
if (delay === undefined) { return ...; }, hovering overdelayon the next line showsnumber, becauseundefinedcan’t get past the return. A second check,delay === 0, returnson timeforHL-0940.
Final Code
Here’s delays.ts at the end of the lesson. The early return on delay === undefined handles the missing report first, so the checker knows delay is a number on every line after it. The delay === 0 check then turns a reported 0 into on time before the last line builds the late note: