In this lesson, you wrote a loudspeaker announcement for every crossing state and made the checker report a state that the switch doesn’t handle.
Key Points
- A switch without a check stays silent. With a fifth member,
DepartedCrossing, added to theCrossingunion and no case for it, the check is still clean. No case matches"departed", soannouncement()reaches its end, andnode announcements.tsprintsundefinedfor the Kittiwake’s 07:00 crossing. - Each case narrows to one member. Inside
case "delayed":, hovering overcrossingshowsDelayedCrossing, the one member with that tag, so that line may readcrossing.newTime. Each case takes the member with its tag out of play, so thedefaultbranch gets only the tags that no case lists. With four cases,crossinginconst unhandled = crossing;has the typeDepartedCrossingthere. neveris the type with no values. You can store something in aneverconstant only when its type isneveras well. When you annotate the constant, as inconst unhandled: never = crossing;, the line says that no crossing should get this far. While a member has no case, the check reports it on that line:Type 'DepartedCrossing' is not assignable to type 'never'.The file still runs, because Node strips the types without checking them, so it still printsundefinedfor the Kittiwake.- An exhaustive switch handles every member. With
case "departed":added, hovering overcrossingin thedefaultbranch showsnever, because no member is left. The checker knows that no crossing can reach the default. There,crossinghas the typenever, which fits theneverconstant, so the check is clean. Node strips: neverwith the other types, so the default keeps a plain assignment. Thenevercheck happens before the run, when the checker reads your code.
Final Code
Here’s announcements.ts with all five states, each with its case, and the never check in the default branch. If Harbor Line adds another state later and the switch has no case for it, the check reports it on that line instead of the loudspeaker saying undefined: