In TypeScript, the types any, unknown, and object are used for different scenarios and have key differences:
any: disables type checking for the variable. It allows you to do anything with the variable without causing compile-time errors. Use it when the type of the object is unknown beforehand and safety is not critical.unknown: also accepts any type, but you need to perform explicit type checking/casting to work with such variables. It is safer than any. Use it for values with unknown types to not lose control over typing.object: a type only for non-primitive objects (objects, arrays, functions) but not for primitives (numbers, strings). It restricts operations to only objects.let a: any = 1; a = 'string'; // OK a(); // OK (but may lead to a runtime error) let b: unknown = 'hello'; b = 5; // OK // b.toUpperCase(); // Error — type checking required if (typeof b === 'string') { console.log(b.toUpperCase()); } let c: object = { key: 'value' }; c = [1, 2, 3]; // OK // c = 1; // Error, as '1' is not an object
Question: What is the benefit of the unknown type if we can use any?
Answer: unknown increases code safety — you cannot perform unchecked operations with the variable like you can with any. You need to explicitly check or cast the type, which eliminates many surprises at runtime.
function handle(value: unknown) { // value.trim(); // Error if (typeof value === 'string') { value.trim(); } }
Story
On the project, it was decided to quickly integrate a third-party library by describing its result through any to avoid dealing with types. As a result, it was discovered at runtime that the library was returning an object with fields instead of an array, which caused widespread errors with the .map() method — this code compiled but failed at execution.
Story
One of the developers used unknown for data coming from the backend but did not add type checks before working with the fields. As a result, TypeScript did not compile the code — and they had to quickly change it to any, which hid potential parsing errors and led to bugs in production due to incorrect data format.
Story
While working with the object type, there was confusion: attempts were made to assign string and number values to a variable of type object. Although no issues were noticed during development, during the review, errors were identified related to object methods not working with primitives. Additional time was required to fix these issues.