Skip to content

Edvins Antonovs

Exploring TypesScript: any vs unknown

In TypeScript, both any and unknown are used to handle values of unknown or dynamic types, but they serve different purposes and come with varying levels of type safety. It is also a popular TypeScript interview question, the answer for which is worth knowing.


any is the most permissive type in TypeScript. It effectively turns off type checking for a variable or value, allowing you to assign and access it in any way you want without type errors.

It is often used when you don't know or don't want to specify the variable type or when working with dynamic data that doesn't have a consistent type.

While any provides much flexibility, it sacrifices type safety because you can perform operations on any value that might not make sense, and TypeScript won't catch these errors.

1let x: any = 10;
2x = 'Hello'; // No type error
3; // No type error, but it might fail at runtime

So what happens in the above code?

let x: any = 10;: We declare a variable x with the type any and initially assign it the value 10. In this case, TypeScript doesn't enforce type checking, so we can assign any type of value to x.

x = 'Hello';: We then reassign x to a string ('Hello'). TypeScript doesn't raise any type errors here because x is of type any, and type checking is effectively disabled for it.;: This line doesn't produce a TypeScript type error because x is still of type any, which means TypeScript allows us to call any method on it. However, at runtime, this line will likely result in an error because there is no foo method on a string ('Hello'). TypeScript can't catch such errors because we've chosen to use the any type.


unknown is a safer alternative to any. It represents a value whose type is not known at compile time, similar to any, but with stricter type checking. You cannot perform arbitrary operations on an unknown value. You must first assert or narrow down its type before working with it. Using unknown forces you to be explicit about handling type conversions, making your code more predictable and safer.

1let y: unknown = 10;
2y = 'Hello'; // This is allowed
4if (typeof y === 'string') {
5 console.log(y.toUpperCase()); // OK, type narrowed to string

In summary, I prefer using unknown over any when dealing with values of unknown types, as it provides better type safety by requiring explicit type checks and conversions. Only use any when working with legacy code or situations where strict typing is not feasible or practical. Using unknown encourages more type-safe code and better compatibility with TypeScript's type system.

© 2024 by Edvins Antonovs. All rights reserved.