← Back to TypeScript Course | Chapter 23: Performance and Best Practices | Lesson 2 of 7

Prefer unknown over any

unknown represents a value whose type is not yet known while keeping TypeScript's safety checks enabled. Before using an unknown value, you must narrow it to a more specific type.

unknown Accepts Any Value

Unlike specific types, unknown can hold a string, a number, an object, an array, or anything else — but unlike any, it actively prevents unsafe operations on that value until it's been properly narrowed first.

Example: unknown Accepts Any Value

typescript
let value: unknown = "hello";
value = 42;
value = { key: "value" };
console.log(value);

Narrowing unknown

Narrow an unknown value using typeof, instanceof, Array.isArray, direct property checks, or a custom type guard — any of these techniques give TypeScript enough information to treat the value as something more specific afterward.

Example: Narrowing unknown

typescript
function describe(value: unknown): string {
  if (typeof value === "string") return `String: ${value}`;
  if (Array.isArray(value)) return `Array of ${value.length}`;
  return "Unknown type";
}
console.log(describe([1, 2, 3]));

unknown for JSON Data

JSON.parse's return type is any in TypeScript's standard library declarations, so data coming from external JSON should be treated as untrusted — assigning the parsed result to an unknown-typed variable encourages validating it before use.

Example: unknown for JSON Data

typescript
const raw: unknown = JSON.parse('{"name":"Ravi"}');
if (typeof raw === "object" && raw !== null && "name" in raw) {
  console.log((raw as { name: string }).name);
}

unknown in Error Handling

Caught errors should be treated as unknown rather than Error, since JavaScript permits throwing values that aren't Error objects at all — narrow the caught value before reading message or any other property off it.

Example: unknown in Error Handling

typescript
try {
  throw new Error("failed");
} catch (err: unknown) {
  if (err instanceof Error) console.log(err.message);
}

unknown in Generic APIs

unknown is well suited to generic utility functions where the implementation shouldn't assume anything about the value's shape, preserving safety internally while still letting callers supply whatever type they need.

Example: unknown in Generic APIs

typescript
function storeValue(key: string, value: unknown): void {
  console.log(`Storing ${key} without assuming its shape`);
}
storeValue("config", { debug: true });
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.