Untrusted input boundaries
Parse JSON or consume external data before validating its runtime shape.
TypeScript · Const
unknown is TypeScript’s safe top type for values whose runtime type is not yet known. It accepts values of any type, but requires narrowing or an assertion before most use.
unknown can hold any value, but TypeScript prevents assigning it to a specific type or performing ordinary operations until control-flow analysis or an assertion narrows it. This makes it a safer boundary type than any for dynamic inputs and API values.
let value: unknown;unknown is a top type intended to represent a value whose specific type is not yet known.unknown variable.unknown instead of any when accepting arbitrary values but still requiring safe consumption.unknown value before narrowing or asserting it.function parseId(value: unknown): string {
if (typeof value === "string") return value;
if (typeof value === "number") return String(value);
throw new TypeError("Expected a string or number");
}
const id = parseId(JSON.parse('"user-42"'));The input remains safely usable only after runtime checks narrow it to a supported type.
Parse JSON or consume external data before validating its runtime shape.
Design APIs that accept arbitrary values without permitting unchecked operations.
Represent values passed through generic infrastructure when their concrete type is not available yet.
unknown differ from any?unknown is a type-safe top type: every value can be assigned to it, but it cannot be used as a more specific type without narrowing or an assertion. Unlike any, it forces the consumer to establish what the value is before using it.
Follow-up: How would you safely consume an unknown JSON value? First narrow its runtime shape with checks or a user-defined type guard, then access only the properties established by those checks.
A value of type unknown may be assigned from any value, but direct operations and assignments to concrete types are rejected. Control-flow narrowing, such as typeof checks, can refine it to a usable type.
Follow-up: What happens if you only assert the type? The compiler accepts the assertion, but the assertion does not validate runtime data, so a guard is safer for untrusted input.
unknown useful in a large codebase?Use unknown at boundaries where a value may have any runtime type, such as parsed or externally supplied data. Then validate or narrow it before passing it into typed application code.
Follow-up: Why prefer it for a pass-through API over any? It preserves safety because downstream code cannot accidentally perform unchecked operations on the value.
anyneverNarrowingType assertionsControl flow analysis