Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readTypeScript
#TypeScript#Type Safety#Best Practices
3D illustration contrasting a hazardous red open any conduit with a secure blue unknown chamber guarded by verification gates

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

  • any is assignable to and from every type. unknown is assignable from every type but assignable only to unknown (and any).
  • Reading a property, calling, or indexing an unknown value is a compile error until a type guard narrows it; on any everything is allowed and nothing is checked.
  • any infects the call graph: a function returning any returns any to every caller, and a generic inferred from any collapses to any.
  • unknown is the correct type for parsed JSON, caught errors (useUnknownInCatchVariables), third-party callbacks, and any value crossing a trust boundary.
  • never is the opposite — no values at all — and the two are easy to confuse in exhaustive checks and impossible-state assertions.
  • unknown narrows like any other union: typeof, instanceof, in, equality, and user-defined predicates all work on it.
  • any still 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

typescript
// 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

Propertyanyunknownnever
Assignable from any typeyesyesno
Assignable to any typeyesno (only any/unknown)yes (unreachable)
Property accessallowed, uncheckederror until narrowedallowed (unreachable code)
Callableallowed, uncheckederror until narrowedallowed (unreachable code)
typeof resultanyunknownnever
Contaminates callersyesnono
Correct useescape hatch, migrationboundary inputexhaustive checks, impossible states
Catches typos silentlyyesnono

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

typescript
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 once

Every 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

typescript
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 later

A 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

typescript
// 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 lie

The 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

typescript
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

typescript
// 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 symptomCauseFix
'x' is of type 'unknown'reading a property before narrowingadd a typeof/in/instanceof guard
Type 'unknown' is not assignable to type 'string'assigning a raw boundary valuevalidate, then assign the constructed value
Type 'any' is not assignable on an index signatureany used where a specific value type is requirednarrow to unknown, then to the concrete type
Object is of type 'unknown' after JSON.parse under a typed wrapperthe wrapper's generic defaulted to unknownparse into a validated type with a guard
Unsafe member access .x on an any value (lint)any from a library or a castshadow it as unknown at the boundary
Type checking silently stops after a callthe function returns anyannotate its return type, or wrap it with a check
catch block shows Cannot find name 'message'useUnknownInCatchVariables in strict modenarrow with instanceof Error
Exhaustive switch compiles after a union member is addedthe default branch returns any or nothingreturn 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 tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.