Software Development

Should I use 'unknown' or 'any' when migrating a legacy JavaScript project to TypeScript?

LA Asked by Laura Mitchell · 22-11-2023
0 upvotes 12,064 views 0 comments
The question

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

0
PA
Answered on 05-01-2024

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. 

0
RI
Answered on 10-01-2024

If we use 'unknown', doesn't that require a lot of redundant type-guard boilerplate code that might slow down our sprint velocity significantly? 

JO 12-01-2024

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.

0
MA
Answered on 15-01-2024

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.

LA 16-01-2024

I like this hybrid approach, Mary. It balances the need for speed during migration with the eventual goal of reaching full type safety.

Share your thoughts

Your email address will not be published. Required fields are marked (*)

Professional Counselling Session

Still have questions?
Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Request a Call Back

Search Online

We Accept

We Accept

Follow Us

"PMI®", "PMBOK®", "PMP®", "CAPM®" and "PMI-ACP®" are registered marks of the Project Management Institute, Inc. | "CSM", "CST" are Registered Trade Marks of The Scrum Alliance, USA. | COBIT® is a trademark of ISACA® registered in the United States and other countries.

Book Free Session