We are starting a migration of a large JS codebase. My team is divided between using 'any' to speed up the process or 'unknown' for better safety. Which type is more appropriate when the data structure isn't immediately clear but we want to avoid breaking the build?
3 answers
Always lean toward 'unknown' if you care about long-term stability. The major difference is that 'any' effectively turns off the type checker, while 'unknown' forces you to perform some form of type checking (like typeof or an instanceof check) before you can perform operations on the value. This "forced safety" ensures that you don't accidentally call a method that doesn't exist. While it takes slightly more time to implement, it prevents the runtime crashes that 'any' often hides.
If we use 'unknown', doesn't that require a lot of redundant type-guard boilerplate code that might slow down our sprint velocity significantly?
Use 'any' for a quick first pass to get things compiling, but immediately flag them with a TODO to convert them to 'unknown' or a specific interface.
I like this hybrid approach, Mary. It balances the need for speed during migration with the eventual goal of reaching full type safety.
It might seem like a slowdown initially, Richard, but it’s actually a time-saver. The time you spend writing a small type guard is much less than the time you'll spend debugging a "Property undefined" error in production later because an 'any' type let a bug slip through.