Skip to main content

Demystifying the unknown Type in TypeScript

In our journey through TypeScript types, we've explored the "any" type. Now, let's dive into another intriguing type: "unknown". At first glance, "unknown" may seem similar to "any", but it holds nuanced differences crucial for TypeScript developers.

Understanding "unknown"

"unknown" in TypeScript is akin to a more controlled version of "any". While both types can hold any value, "unknown" adds an extra layer of safety, demanding type checking before performing operations on its values.

Example:

function multiByTwo(number: unknown) {
if (typeof number === "number") {
return number * 2;
}
return "Please provide a valid number";
}

console.log(multiByTwo(4)); // Output: 8
console.log(multiByTwo("john")); // Output: Please provide a valid number

In this example, the multiByTwo function takes a parameter of type "unknown". TypeScript, by default, will not allow any operation on this parameter without proper type checking. This is the primary distinction between "unknown" and " any".

The Safety Net of "unknown"

When a variable is of type "unknown", TypeScript forces you to explicitly check the type of value before using it. This requirement adds a layer of safety, ensuring that you don't inadvertently perform operations on types that don't support them.

Why is it better than "any"?

With "any", TypeScript leaves it up to you to ensure you're using the right types. It's a free-for-all that can lead to unpredictable behavior and errors. In contrast, "unknown" nudges you to confirm types before proceeding, reducing the chance of runtime errors.

Use Case

"unknown" is particularly helpful when you're dealing with values whose types you can't predict, but you still want to maintain type safety. It's a way to tell TypeScript, "I don't know what this is yet, but I'll figure it out before I use it."

In Conclusion

While "unknown" might not be as frequently used as other types, it's a valuable tool in scenarios where type safety is paramount, and the type of a value isn't immediately clear. It offers a controlled environment, ensuring that you, as a developer, check and confirm types, thus leading to more robust and error-resistant code.

Remember, while "unknown" offers more safety compared to "any", it should still be used judiciously. Strive to use more specific types whenever possible, and reserve "unknown" for situations where the type really can't be predicted or inferred upfront.

What Can You Do Next 🙏😊

If you liked the article, consider subscribing to Cloudaffle, my YouTube Channel, where I keep posting in-depth tutorials and all edutainment stuff for software developers.

YouTube @cloudaffle