"unknown" vs. "any"

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for "unknown" vs. "any"

"unknown" Vs "any": Unraveling the Mystery 🕵️‍♂️

Are you puzzled by the introduction of TypeScript's new type, "unknown"? 🤔 Are you wondering how it differs from the familiar "any" type and when to use one over the other? Don't worry! We've got you covered! 📚

Understanding the Basics 📖

Before delving into the comparison, let's quickly refresh our knowledge about these two types:

  • "any" type: It represents a lack of static type checking and allows values of any type to be assigned to it. It essentially throws away type safety.

  • "unknown" type: Introduced in TypeScript 3.0, it provides a safer alternative to "any" by preserving type checking. Values of unknown type can only be assigned to variables of type "unknown" or "any" without the need for type assertions or additional narrowing.

The Dilemma: "unknown" or "any"? 🤷‍♂️

Now, let's tackle the burning question: When should we use "unknown" instead of "any"? 🔥

The answer lies in our intention and the level of type safety we desire. If we are unsure about the type of a value or if it could be of multiple types, "unknown" comes to the rescue. By using "unknown," we acknowledge the ambiguity and enforce handling the value in a type-safe manner.

On the other hand, if we genuinely need to accept values of any type and disable static type checking temporarily, "any" is still the way to go. However, it's important to remember that using "any" excessively can decrease the advantages of using TypeScript's strict type system.

💡 Use Case Example

Consider a scenario where we receive user-provided input from an API. We are unsure about the exact shape or type of the data. Here's how we can handle it using both types:

function processInput(input: unknown) {
  if (typeof input === 'string') {
    // Handle string input
  } else if (typeof input === 'number') {
    // Handle number input
  } else {
    // Handle other cases
  }
}

In this example, using "unknown" gives us the flexibility to perform type narrowing without resorting to type assertions.

Release the Full Potential: Time for "unknown"! ⏱️

Now that we have a better understanding of "unknown" and when to leverage its advantages, it's time to upgrade your TypeScript code! 🚀

  1. Identify scenarios where the type of a value is uncertain or could be multiple types.

  2. Replace occurrences of "any" with "unknown" in those scenarios.

  3. Safely handle the "unknown" value by using type guards or narrowing techniques.

  4. Enjoy the benefits of enhanced type safety while still preserving flexibility.

Join the Quest for Type Safety! 🔍

Now that the veil of confusion has been lifted, it's your turn to embark on the journey towards type safety! We challenge you to refactor any instances of "any" that can be replaced with the more precise "unknown" type. Share your success stories, code snippets, and learnings with the community in the comments section below. Let's strengthen our TypeScript skills together! 💪

Remember, embracing "unknown" not only enhances the robustness of your code but also elevates your TypeScript prowess to a whole new level. Happy coding! 👩‍💻👨‍💻

Stay tuned for more such insightful content! Keep exploring, experimenting, and evolving! 🌟

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my