unknown (TypeScript)

`unknown` is the type-safe counterpart of `any`. It can hold any value, but TypeScript won't let you use it until you narrow it down to a specific type first.

TypeScript

Both `any` and `unknown` accept any value, but they behave oppositely afterward. With `any` you can do anything; with `unknown` you can do nothing until you prove the type with a check or assertion.

`unknown` is the recommended type for values whose shape you don't control, such as parsed JSON or data from an API, because it forces you to validate before use.

Examples

TypeScript

let value: unknown = "hello";

if (typeof value === "string") {
  console.log(value.toUpperCase());
}

Output:

HELLO

TypeScript — Compile error: 'value' is of type 'unknown'.

let value: unknown = "hi";
value.toUpperCase();

Learn it in a lesson

See also

Back to the Dictionary