Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Primitive and Special Types

The TypeScript unknown type

Reference for unknown in TypeScript: assignability, narrowing with typeof, instanceof and type guards, unknown versus any, catch variables and validation.

unknown is the type-safe counterpart of any. Every value can be assigned to unknown, but you cannot do anything with an unknown value until you have narrowed it to something more specific. It is the right type for data whose shape you have not verified: parsed JSON, catch variables, message payloads, function arguments from outside.

The compiler demands a check (typeof, instanceof, a type predicate, or a validation library) before you read properties or call methods.

TypeScript
let input: unknown = JSON.parse("[1,2,3]");
if (Array.isArray(input)) {
  console.log(input.length);
}

Try it

TypeScript Narrowing an unknown value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Type guards, catch and Zod-style parsing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
let u: unknown;
function handle(input: unknown): void {}
const result = value as string;       // assertion from unknown is allowed
Operation on unknown Allowed?
Assign any value to it Yes.
Assign it to unknown or any Yes.
Assign it to any other type No, without narrowing or an assertion.
Property access, call, arithmetic No (error TS18046 "'x' is of type 'unknown'").
===, !==, typeof, instanceof, in Yes, and these narrow it.

Usage notes

  • Top type. unknown is at the top of the type hierarchy: everything is assignable to it. never is at the bottom.
  • Unions and intersections. T | unknown is unknown; T & unknown is T.
  • Index access. Narrow to object and in first: "name" in value narrows value to object & Record<"name", unknown>.
  • Assertions are unchecked. value as Point compiles but verifies nothing. Use a type guard or a schema validator for external data.
  • catch (error) is unknown under strict (useUnknownInCatchVariables); check error instanceof Error before reading .message.
  • Generic defaults. Write function parse<T = unknown>(...) rather than defaulting to any.
  • Use it for JSON input, postMessage events, plugin hooks, Promise.reject reasons and wrapper functions that pass values through untouched.
  • Comparison with {} and object: they exclude null/undefined (and primitives, for object) while unknown includes everything.