With tongue firmly in cheek, I tweeted the following:
Perhaps my favorite TypeScript tip pic.twitter.com/SgLAndod3a— Kyle Shevlin (@kyleshevlin) January 22, 2024
The response the post received was a lot larger than I was expecting, so I thought I’d take a moment to explain why this is both a tip and a joke at the same time.
any is ok
If you’ve written TypeScript for long enough, then I am willing to bet
any has come to your rescue a time or two.
Add to this any time pressure or consideration between value created versus the time it’s taking to do so, and you’ll find yourself in a situation where it is just not worth it to solve that hairy type problem right now. That’s where the
TODO type comes in handy.
type TODO = any
any was appropriate. Making it a
TODO provides some signal that perhaps a time may come where it can be updated and improved.
Don’t forget, you don’t have to name it
TODO either. You can name it something more specific. Perhaps you prefix a typename with
UNSAFE_ or something similar to signal that you’ve opted out of type safety.
Joke: You shouldn’t use
While there are appropriate times to use the
TODO type, it definitely should not be abused. If many parts, or particularly important parts, are littered with
any types, then you may want to consider if it’s possible to devote more time to getting the types correct.
We want to use
TODO purposefully, as the very rare escape hatch and a signal that the following code is unsafe. Don’t just use them to hide something under the proverbial rug, use them to make it clear that something requires further attention when possible.
I use a VSCode extension, TODO Highlight, that highlights keywords in your editor. With a few tweaks to the settings, the extension will highlight every use of
TODO in your app. That way, you never visually miss where you have them.
TODO can be useful in a pinch, especially when considering the time/value tradeoff. Do treat them like a real
TODO and try and fix them when you have time. Use either type sparingly.
Lastly, keep improving your TypeScript skills and you’ll find you reach for these types less often.