Skip to main content

Command Palette

Search for a command to run...

Type Safety in TypeScript - Unknown vs Any

Updated
3 min read
Type Safety in TypeScript - Unknown vs Any
S

Hi there 👋, I’m Sachin Chaurasiya, a software engineer with over 4 years of experience in building scalable, performant, and user-centric products. I enjoy solving challenging problems and creating products that make a difference for users.

Collaboration is a big part of my work. I’ve worked closely with designers, backend engineers, and other teams to deliver solutions that are efficient and easy to use. I also enjoy mentoring and guiding other engineers to help them grow in their careers.

I believe in taking ownership of my work and always strive to go the extra mile to ensure high-quality results. Beyond work, I love sharing knowledge through writing technical blogs and contributing to open-source projects, and I am currently contributing to OpenMetadata and ReactPlay.

If you’re looking for someone who’s passionate about building impactful products and working as part of a team, let’s connect and create something amazing together. You can reach me at sachinchaurasiya.dev@gmail.com.

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.

Exploring unknown

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.

Exploring any

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.

When to use unknown

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.

When to use any

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.

Conclusion

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.

Connect with me