Unknown Type

What

The unknown type is the type-safe counterpart of any. Like any, it can represent any value, but unlike any, it forbids you from using that value until you explicitly narrow its type.

How

You must perform a type check (like typeof or instanceof) before performing operations on an unknown value:

function process(data: unknown) {
  // Error: Object is of type 'unknown'
  // data.toLowerCase();

  if (typeof data === "string") {
    // Narrowed to string - this is now safe
    console.log(data.toLowerCase());
  }
}

Why

Using any effectively turns off type checking, which can lead to runtime crashes. unknown provides the same flexibility for incoming data (like API responses) but forces you to validate the data at the boundaries of your program, ensuring internal type safety.

Summary

Use unknown whenever you are dealing with values from the outside world that you haven’t validated yet.