Should we use static types in JavaScript or not?
The first programming languages I learned were JavaScript and Python, both of which are dynamically-typed languages.
But my foray into static types have added a whole new dimension to how I think about programming. For example, even though I found the Elm compiler errors overwhelming at first, defining types and “pleasing the compiler” became second nature, and actually improved my code thinking. Plus, there's nothing more liberating than an intelligent robot telling me when I'm doing something wrong and how to fix it.
Despite the tradeoffs that come with types like verbosity and the upfront investment to master them, the safety and correctness that types add to our programs make these “disadvantages” less of an issue for me personally.
Dynamic typing feels faster and easier, but it sometimes loses ground once you actually try to make a program run in the wild. At the same time, you can talk to any Java developer who's had to work with more complicated generic type definitions and they'll tell you all about how much they hate types.
Ultimately, there's no silver bullet. My personal approach is to favor using types under these circumstances:
- The program is critical to your business
- The program is likely to be refactored as your needs evolve
- The program is complex and has many moving parts
- The program is maintained by a large team of developers who need to be able to grasp and understand the code quickly and accurately
On the flip side, I'd consider opting out of types in these types of situations:
- The code is short-lived and non-critical
- You're prototyping and trying to move as quickly as possible
- The program is small and/or simple
- You're the only developer
The beauty of being a JavaScript developer today is that because of tools like Flow and TypeScript, we finally have a choice of whether to use static types or good ol' vanilla JavaScript.
Conclusion
I hope this post helped you get a feel for why types matter, how to use them, and most importantly when to use them.
Being able to toggle between dynamic and static types is a powerful tool for the JavaScript community – and exciting :)
More questions? As always, ping me in the comments to keep the conversation going.
Top comments (0)