We all know issues are cheaper to fix earlier in a project’s lifecycle, but finding issues before they ship isn’t always easy. As web developers we rely on a growing set of tools to help, but the out-of-the-box configuration for a given tool isn’t always the one we need. Some projects have unique needs and sometimes good options are simply off-by-default — typically to avoid breaking existing users.
A good option
One such good option is TypeScript’s
strict compiler option. We were new to TypeScript when first starting webhint and missed turning on
strict early in the project. Recently we enabled it and are pretty happy with the results. Going strict has a number of benefits, but the included
strictNullChecks option proved both the most involved to adapt and the most beneficial to adopt. Ultimately we had to make changes across a large number of files in our project, but we caught two types of issues in the process.
The first and more serious issues were missing
null checks waiting to become production problems. Take the following function for example:
strictNullChecks a caller can pass
null for any of the parameters without raising an error. Yet this code didn’t expect
null still compiles, but could break at runtime. Turning on
strictNullChecks initially makes passing
null for any parameter a compile-time error. However we can now be explicit about what’s allowed so only expected
null values can be passed in. In this case we updated not only the signature, but the implementation as well.
The second set of issues were redundant
null checks, typically in calling functions. Here’s another example:
strictNullChecks callers had to look at the implementation of this function to figure out if it was safe to pass
null (and hope no one changed it in the future). After enabling the option and updating the signature, callers now know exactly what’s safe and what isn’t.
Finding more good options
The challenge with good options like
strict is we don’t always know they exist or if they apply to our project. That’s where webhint comes in. Using webhint via the command line or extension for Visual Studio Code provides a “hint” to enable
strict compilation for your own projects:
Plus webhint can point out other options to help reduce bundle size (and provides general web development hints beyond TypeScript). Of course if you’re not ready to cut-over to a particular option just yet, you can adjust your
.hintrc to downgrade to a warning (or turn it off altogether):
The point is webhint helps you find options and best practices you hadn’t realized you didn’t know. Then you get to decide what’s most important for your projects.
Make the change
But really, you should turn on TypeScript’s
strict option. Depending on your code the transition may not be easy, but the increased confidence will be worth it and you’ll probably fix a few bugs along the way. And if you’re starting a new project make sure it’s turned on from the start — you’ll be glad you did.