Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
👋 Hi! I'm Dastan, author of Hack Frontend. Always open to professional networking => connect with me on LinkedIn.
In TypeScript there are two types that can be used to represent any values: any and unknown. Although both types allow working with any values, their behavior and safety in the context of types differ.
The any type is used when you want to indicate that a value can be of any type. This allows working with variables whose types aren't known at compile time, but at the same time any removes type restrictions, allowing you to do anything with the variable.
any usage example
let value: any;
value = 42; // Number
value = "Hello"; // String
value = { name: "John" }; // Object
value.someMethod(); // Error won't be detected at compile time
The unknown type is a safer alternative to any. With unknown you can still work with a variable of any type, but you need to check its type before performing operations on it. That is, unlike any, you won't be able to perform operations with an unknown type variable without checking its type.
unknown usage example
let value: unknown;
value = 42; // Number
value = "Hello"; // String
// Compilation error: can't call methods on `unknown` type
value.someMethod();
// Need to perform type check before using
if (typeof value === "string") {
console.log(value.toUpperCase()); // Now it's safe
}
any when you know for sure that you don't need to check the type, or in cases where the type can't be precisely determined, for example, when working with dynamic data or third-party libraries without types.unknown when you need to work with variables whose type is unknown, but you want to maintain type safety by performing explicit type checking before using data.