Fixing Warnings of TypeScript Strict Mode Violation After "Tour of Heroes" Tutorial
Once I've reached the end of the Angular "Tour of Heroes" tutorial, I went back to address something from the beginning. When I created my Angular project, I added the --strict
flag for the optional "Strict Mode". My motivation was the belief that, since I'm starting from scratch, I might as well learn it under enforcement of best practices. I soon realized this was also adding an extra burden on myself for following the tutorial, because the example code does not always follow strict mode. This means when something goes wrong, I might have copied the tutorial code incorrectly, but it's also possible I copied correctly but it's just doesn't conform to strict mode.
As a beginner, I really didn't need this extra work, since I had enough problems with basics on my own. But I decided to forge onward and figure it out as I went. During the tutorial, I fixed strict mode errors in two categories:
- Something so trivial that I could fix quickly and move on.
- Something so serious that compilation failed and I had to fix it before I could move on.
In between those two extremes were errors that were not trivial, but only resulted in compilation warnings that I could ignore and address later. They are visible in this GitHub commit:
I first had to understand what the code was doing, which was why I imported MessageService
to gain access to logging. The compiler warnings were both about uninitialized variables, but the correct solution was different for the two cases.
For the hero input field, the tutorial code logic treats undefined
as a valid case. It is in fact dependent on undefined
hero to know when not to display the detail panel. Once I understood this behavior, I felt declaring the variable type as a Hero OR undefined was the correct path forward.
For the Observable collection of Heroes, the correct answer is different. The code never counts on undefined being a valid value, so I did not need to do the if/else checks to handle it as an "OR undefined" value. What I needed instead was an initial value of a degenerate Observable that does nothing until we can get a real Observable. Combing through RxJS documentation I saw this was recognized as a need and was actually done in a few different ways that have since been deprecated. The current recommendation is to use the constant defined as EMPTY, which is what I used to resolve the strict mode errors.