TypeScript unknown vs any: Type Safety, Type Guards, and Best Practices
Why any contaminates every caller while unknown forces the check at the boundary, with validation functions, generic inference traps, and the few places any is honestly correct.

any disables type checking for everything it touches; unknown accepts any value but permits nothing until the code proves what it is. The difference is not strictness for its own sake: any propagates invisibly through assignments, returns, and generics, so a single untyped boundary silently removes checking from every caller downstream, while unknown forces the conversion to happen at the boundary, where the runtime shape is actually known.
Quick Summary
anyis assignable to and from every type.unknownis assignable from every type but assignable only tounknown(andany).- Reading a property, calling, or indexing an
unknownvalue is a compile error until a type guard narrows it; onanyeverything is allowed and nothing is checked. anyinfects the call graph: a function returninganyreturnsanyto every caller, and a generic inferred fromanycollapses toany.unknownis the correct type for parsed JSON, caught errors (useUnknownInCatchVariables), third-party callbacks, and any value crossing a trust boundary.neveris the opposite — no values at all — and the two are easy to confuse in exhaustive checks and impossible-state assertions.unknownnarrows like any other union:typeof,instanceof,in, equality, and user-defined predicates all work on it.anystill has legitimate uses: migrating untyped JavaScript, adapting a library whose types are wrong, and deliberately escaping a constraint for a single expression.
Basic syntax and type signatures
// any: assignable both ways, no checks.
let a: any = JSON.parse("{}");
a.anything.deeply.nested(); // compiles, throws at runtime
const s: string = a; // compiles, may be undefined
// unknown: assignable in, nothing out.
let u: unknown = JSON.parse("{}");
// u.anything; // error: 'u' is of type 'unknown'
const s2: string = u; // error: Type 'unknown' is not assignable to type 'string'
// Narrowing is the only way out.
if (typeof u === "object" && u !== null && "id" in u) {
const id = (u as { id: unknown }).id;
if (typeof id === "number") {
const n: number = id; // ok
}
}
// A guard function packages the proof for reuse.
function isRecord(v: unknown): v is Record<string, unknown> {
return typeof v === "object" && v !== null && !Array.isArray(v);
}
// `unknown` in catch clauses is the default under strict mode.
try { /* ... */ } catch (err: unknown) {
if (err instanceof Error) console.error(err.message);
}The isRecord guard is worth writing once per project: nearly every JSON validation starts by proving the value is a non-null, non-array object, and the guard keeps that proof out of every call site.
Comparison
| Property | any | unknown | never |
|---|---|---|---|
| Assignable from any type | yes | yes | no |
| Assignable to any type | yes | no (only any/unknown) | yes (unreachable) |
| Property access | allowed, unchecked | error until narrowed | allowed (unreachable code) |
| Callable | allowed, unchecked | error until narrowed | allowed (unreachable code) |
typeof result | any | unknown | never |
| Contaminates callers | yes | no | no |
| Correct use | escape hatch, migration | boundary input | exhaustive checks, impossible states |
| Catches typos silently | yes | no | no |
never belongs in the table because it is what an exhaustive switch returns after every case is handled: with strict and a default: assertNever(x) branch, adding a union member turns into a compile error at exactly the place that needs updating.
Practical edge cases and deep dives
1. A boundary function that validates instead of casting
type User = { id: number; name: string; tags: string[] };
function parseUser(input: unknown): User {
if (typeof input !== "object" || input === null) {
throw new TypeError("user: expected object");
}
const o = input as Record<string, unknown>;
if (typeof o.id !== "number" || Number.isNaN(o.id)) {
throw new TypeError("user.id: expected number");
}
if (typeof o.name !== "string") {
throw new TypeError("user.name: expected string");
}
if (!Array.isArray(o.tags) || !o.tags.every((t) => typeof t === "string")) {
throw new TypeError("user.tags: expected string[]");
}
return { id: o.id, name: o.name, tags: o.tags };
}
const raw: unknown = await res.json();
const user = parseUser(raw); // User from here on, proven onceEvery check produces its own useful error, and the returned object is constructed rather than asserted, so extra properties from the payload do not leak into the type. With any at the parameter, parseUser would compile even if it returned the wrong shape, and with as User it would compile while lying. The Record<string, unknown> cast is the one permitted step: it changes how the proven object is accessed, not what has been proven about it.
2. Generics: how any collapses an inferred signature
declare function identity<T>(value: T): T;
const x = identity<any>(undefined); // any
const y = identity(undefined); // undefined
function tap<T>(value: T, fn: (v: T) => void): T {
fn(value);
return value;
}
declare const payload: any;
const z = tap(payload, (v) => v.missing.method()); // no error, crashes laterA generic parameter inferred from an any argument becomes any, and every use of T inside the function body loses its check. With unknown, tap would require the callback parameter to deal with unknown, which pushes the narrowing to the place that has the information. The rule: unknown at the input, T in the middle, the concrete type at the output.
3. any in library types and the containment wrapper
// A third-party declaration that returns any.
declare const legacy: { get(key: string): any };
// Contain it at one point and never let it travel further.
function readSetting(key: string): string | undefined {
const value: unknown = legacy.get(key);
return typeof value === "string" ? value : undefined;
}
// Any does not satisfy index-signature constraints the way a typed value does.
type Dict = { [k: string]: unknown };
// const bad: Dict = 1 as any; // compiles, but the assertion is the lieThe const value: unknown = ... line is the whole technique: an any assigned to an unknown loses its powers, and the rest of the function is checked. Without that line, value.trim() would compile against a number and fail in production.
4. Narrowing unknown through a Map and a discriminated result
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
const cache = new Map<string, unknown>();
function cached<T>(key: string, parse: (v: unknown) => T | undefined): T | undefined {
if (!cache.has(key)) return undefined;
const value = cache.get(key); // T | undefined
return parse(value);
}
function parseNumber(v: unknown): number | undefined {
if (typeof v === "number" && Number.isFinite(v)) return v;
if (typeof v === "string" && v.trim() !== "" && !Number.isNaN(Number(v))) {
return Number(v);
}
return undefined;
}
const n = cached("port", parseNumber);
if (n !== undefined) start(n);Map<string, unknown> forces every read to be re-proven, which is correct for a cache whose values came from different parsers. The alternative, Map<string, any>, makes cached("port", parseNumber) return any and quietly discards the fact that parseNumber may return undefined — the exact difference between a null check and a crash.
5. Where any is honestly correct: adapting an untyped module
// untyped.d.ts — the module ships no types and its runtime API is stable.
declare module "legacy-analytics" {
const api: {
track: (event: string, props?: Record<string, unknown>) => void;
page: (path: string) => void;
};
export default api;
}
// When even that is impossible, isolate it.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mod = (await import("legacy-analytics")) as any;
const track = (event: string, props?: Record<string, unknown>) => mod.default.track(event, props);A short hand-written declaration is usually cheaper than a cast and gives the whole project one place to fix when the library gains types. When nothing better is possible, one disabled lint rule at one line is easier to audit than an any that spreads through a file.
Common mistakes and compiler errors
| Error or symptom | Cause | Fix |
|---|---|---|
'x' is of type 'unknown' | reading a property before narrowing | add a typeof/in/instanceof guard |
Type 'unknown' is not assignable to type 'string' | assigning a raw boundary value | validate, then assign the constructed value |
Type 'any' is not assignable on an index signature | any used where a specific value type is required | narrow to unknown, then to the concrete type |
Object is of type 'unknown' after JSON.parse under a typed wrapper | the wrapper's generic defaulted to unknown | parse into a validated type with a guard |
Unsafe member access .x on an any value (lint) | any from a library or a cast | shadow it as unknown at the boundary |
| Type checking silently stops after a call | the function returns any | annotate its return type, or wrap it with a check |
catch block shows Cannot find name 'message' | useUnknownInCatchVariables in strict mode | narrow with instanceof Error |
| Exhaustive switch compiles after a union member is added | the default branch returns any or nothing | return never via an assertNever helper |
The choice reduces to one question per value: where is the code that knows what this is? If the answer is "the caller, after a parse", the type is unknown and the parse does the work. If the answer is "nobody, and I cannot fix that now", the type is any and the honest move is to confine it to one line, comment why, and route everything else through unknown.
Try matching browser tools
All toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTypeScript Generic Parameter Defaults: Syntax, Precedence, and Inference
When a default applies and when inference wins, defaults that reference earlier parameters, and how a defaulted type parameter keeps a library change non-breaking.
TypeScript Branded Types: Nominal Typing, Type Tags, and Validation
How a phantom property makes two strings incompatible, unique symbol brands, unit-typed numbers, and the places where a brand quietly disappears.
TypeScript Ambient Declarations: .d.ts Files, declare, and declare global
How declare and .d.ts files describe runtime values, wildcard modules for assets, declare global with var, and module augmentation of third-party types.
TypeScript Discriminated Unions: Exhaustiveness Checking and the never Type
Why the discriminant must be a literal, how never closes an exhaustive switch, and the duplicate-discriminant bug that lets a missing case compile.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.