Few days ago, I finished reading Dan Vanderkam’s Effective TypeScript over a long flight (8 hours to be exact!). The book is concisely written with great practical advices. While I recommend reading the full book, here are some of my favorite tips.
1. Use `readonly` to prevent errors from mutating objects
When an array or a tuple is marked as
readonly, TS will error when the user tries to to add, remove, or update items in those objects. This is especially helpful in functional programming to avoid side effects.
2. Prefer function expressions over function declarations for type reusability
When writing utilities that have the same function signatures, it can get a little repetitive. Below, you see three cart related functions that require input and output types to be written out again each time.
To keep it DRY, you can assign the entire signature to a function type and switch to using function expressions.
3. Prefer unknown over any to get better type safety
any can be a useful escape hatch, but there are also good reasons to avoid it. It doesn’t guarantee any type safety and it hides errors from the consumers up the call chain. With
unknown type, TypeScript will correctly surface errors such as calling non existent methods.
If you as a developer have more knowledge about the type than the compiler, you can also use
unknown with double assertions to clarify the intent.
4. Lean into JSDoc or TSDoc style comments for better development experience
In most cases, you should avoid having type information in comments. However, if you are migrating and using JS to enable TS, or if you want to provide additional information about the function, JSDoc or TSDoc is a great way to get type checking and integrate with your IDE.
Note VSCode shows the properly formatted comments in the tooltip.
That’s it! I chose these tips because they’re immediately applicable to improving our existing codebase. I hope you found them useful too.