Codectionary / Developer documentation / TypeScript

unknown at Input Boundaries

unknown accepts a value without granting permission to use it as a specific type.

What it is and why to use it

unknown accepts a value without granting permission to use it as a specific type. It is useful at JSON, message or library boundaries where the application must check the value before calling methods. Unlike any, it makes the checking step visible to the compiler.

Common mistakes and limitations

A type assertion such as input as string bypasses the useful restriction without checking anything. Do not replace unknown with any just to silence errors. A typeof object check alone also accepts null and does not verify object properties.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

const input: unknown = value;

Examples

unknown at Input Boundaries

Standalone TypeScript 5.8+ example; expected output is explained below.

function label(input: unknown): string {
  if (typeof input === "string") return input.trim();
  return "Not text";
}
console.log(label("  John  "));
console.log(label(42));
  1. label accepts either input without claiming its shape in advance.
  2. typeof narrows input to string in the first branch, making trim safe to call.
  3. The number takes the fallback branch. This pattern is a first step in validating a message, although checking a complete object requires checking its fields too.
  4. Expected output: John Not text

Best practices

  • A type assertion such as input as string bypasses the useful restriction without checking anything. Do not replace unknown with any just to silence errors. A typeof object check alone also accepts null and does not verify object properties.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading