Sobes.tech
Middle

What is unknown? How is it better than any?

sobes.tech AI

Answer from AI

In TypeScript, unknown is a type that represents a value of unknown type. It is safer than any because variables of type unknown cannot be used directly in operations without prior type checking.

Why unknown is better than any:

  • any disables type checking, allowing any operation on the variable, which can lead to errors.
  • unknown requires explicit type checking or casting before using the value, increasing code safety.

Example:

let value: unknown = 10;

// Error: Object is of type 'unknown'.
// console.log(value.toFixed(2));

if (typeof value === 'number') {
  console.log(value.toFixed(2)); // Now safe
}

Thus, unknown helps write more reliable and safer code compared to any.