Type Safety in TypeScript - Unknown vs Any

Search for a command to run...

No comments yet. Be the first to comment.
OpenAI has brought the revolution in the AI field by creating the ChatGPT and now we can say the actual AI era has started and everyone from individuals to businesses using AI. OpenAI has even created an API to build custom AI solutions like chatbots...
Every October, the developer community buzzes with Hacktoberfest energy. PRs fly, t-shirts are earned, and GitHub turns green. But here's what nobody talks about: what happens in November? For most contributors, the answer is simple: nothing. The rep...

The debate over AI coding agents is missing the most important factor. It’s not about prompt engineering, it’s about understanding the context window. Developers are divided. One side claims coding agents suck. The other insists you’re just using the...

Learnings from a Research Paper

Lately, I have been working on a feature to capture images from media streams and scale them down to reduce their size. This helps save storage and reduce costs before uploading the images to a storage service. For this, I used Canvas to render the i...

AI helps you do more, but only if you know the basics well enough to tell it what you want.

TypeScript is very popular because it adds static typing to JavaScript. This makes the code safer and better quality, which JavaScript developers like. In TypeScript, two types that are often used are unknown and any. They might look the same at first, but they are used for different things. In this article, we will look at unknown and any in more detail and show how they are used with examples.
The unknown type is a safer choice than any. When a variable is of type unknown, TypeScript makes you check the type before you can use that variable. This makes developers clearly state their assumptions, which helps to avoid errors when the code is running.
Think about a situation where you're using data from an API, and you are not sure what the data looks like. Using the unknown helps you deal with this uncertainty in a safe way.
function processData(data: unknown): string {
if (typeof data === 'string') {
return data.toUpperCase();
} else {
// Handle other cases appropriately
return "Invalid data";
}
}
// No compilation error
const result = processData("Hello, TypeScript!");
In simpler terms, using unknown makes sure you double-check what kind of data you have before you do anything with it. This helps prevent mistakes that could happen while the program is running.
On the other hand, any is the most easy-going type in TypeScript. It skips type checking, letting variables of this type to be set to anything without making the code fail to compile. While this freedom can be handy, it means you lose the advantages of static typing.
Think about a situation where you want as much flexibility as possible, and you're sure that your code is type-safe
function processDynamicData(data: any): string {
// No compilation error
return data.toUpperCase();
}
// No compilation error, works as expected
const result1 = processDynamicData("Hello, TypeScript!");
console.log(result1); // Outputs: "HELLO, TYPESCRIPT!"
// No compilation error, but will cause a runtime error
const result2 = processDynamicData(12345);
console.log(result2); // Error: data.toUpperCase is not a function
In simpler terms, using any means you don't have to check the type of data, but it can cause problems if the data type is not what you expected.
Use unknown when you're not sure what kinda variable is, and you want to make sure it's the right kind before you do something with it. This makes your code safer and easier to understand, especially when you're working with data from outside or inputs that can change.
Consider using any when you need maximum flexibility and are confident that type of safety won't be compromised. However, use any sparingly, as its overuse can lead to a loss of the benefits provided by TypeScript's static typing.
When using TypeScript, you can use unknown when you want to be very careful with your code and make sure everything is the right type. any is used when you want to be more flexible, but this can make your code less safe. You should think carefully about which one to use, depending on what your code needs and how confident you are about the types and safety of your code.
That's all for this topic. Thank you for reading! If you found this article helpful, please consider liking, commenting, and sharing it with others.