Prefer unknown over any
In this page:
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
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
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
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
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
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: