Susan Potter
software: Created / Updated

`any` versus `unknown` in TypeScript: When to use one over the other

Understanding the differences between any and unknown is critical to harnessing TypeScript's statically typed powers especially when developing on the edges of TypeScript and JavaScript in legacy codebases. Let this be the blog post I refer JavaScript developer wrapping their heads around the distinction going forward as I advocate for stronger types preferring unknown when you are faced with the choice when you are able.

When it comes to wrangling with uncertain types, unknown emerges as the unsung hero of TypeScript. It swoops in to save the day, providing a safer alternative to the wild and unruly any. Picture unknown as a vigilant guard that demands rigorous type checking before any code can get its hands on the data.

Unlike the reckless freedom of any, unknown keeps the chaos in check. It compels you to exercise caution, forcing explicit type checks and guarding against potential mishaps. It's like strapping on a safety harness before embarking on a daring adventure—sure, it might slow you down a bit, but it guarantees a smoother journey and shields you from disastrous pitfalls.

With unknown, you must prove your worthiness before gaining access to the data. Think of it as a mysterious treasure chest locked with a cryptic puzzle. You need to solve the puzzle, utilizing type guards like `typeof`, `instanceof`, or crafting your custom checks, to unveil the secrets hidden within. This extra layer of scrutiny ensures that you tread carefully and prevent any unexpected surprises.

On the other hand, we have the audacious any, the rogue of TypeScript. It flings open the doors to unrestricted freedom, demolishing all boundaries and renouncing the perks of static typing. Like a reckless adventurer charging headfirst into a treacherous cave without a map, any disregards caution, leaving you vulnerable to unforeseen dangers.

Sure, any offers boundless flexibility, allowing you to toss any value around with reckless abandon. It's the rebel of types, snubbing the safety nets of the compiler and the prying eyes of static analysis. But beware! This unchecked freedom comes at a cost. While it may seem liberating, you're left exposed to the lurking demons of runtime errors, waiting to strike when incompatible operations clash and chaos ensues.

In the battle of unknown versus any, the choice is clear. Embrace the vigilant guardian of types and opt for unknown whenever possible. Its insistence on type checking might seem tedious at first, but it ensures a smoother development journey and keeps you one step ahead of those pesky runtime errors.

But let's not dismiss any entirely. It is the escape hatch required for exceptionally hairy situations. It's the wild card that reluctantly saves the day when all other options contort developer ergonomics beyond your limit.

any

  • Use any when you want to opt out of static typing and have maximum flexibility in assigning and using values.
  • any essentially turns off type checking for the assigned value, allowing it to be freely assigned to any other value or used in any operation without triggering type errors.
  • While any provides flexibility, it sacrifices the benefits of static type checking and can lead to runtime errors if incompatible operations are performed on the value.

unknown

  • Use unknown when you have a value that can be of any type, but you want to enforce type checking before performing any operations on it.
  • unknown is a safer alternative to any because it requires explicit type checking or assertions before performing operations or accessing properties/methods.
  • It provides more type safety and helps catch potential errors at compile-time.
  • You must narrow down the type of an unknown value before using it in specific operations or assignments.

TODO An example of using any versus unknown

Wrapping Up

While any may tempt you with its unruly allure and lower number of keystrokes, it's the watchful guardian unknown that will guide you towards safer programming practices. Embrace the challenge, wield the power of explicit type checking, and bask in the glory of more reliable code. Let unknown be your loyal companion as you embark on a thrilling TypeScript adventure, brimming with type safety and unmatched confidence.

If you enjoyed this content, please consider sharing this link with a friend, following my GitHub, Twitter/X or LinkedIn accounts, or subscribing to my RSS feed.