unknown (type)
The type-safe type for a value that could be anything, which you must narrow before you can use it.
In more detail
Like any, unknown accepts every value, but unlike any it forbids reading properties or calling it until a check proves what it is. It is the right type for network payloads, parsed JSON, storage and caught errors.
Example
function parseWebhook(raw: unknown): WebhookEventRelated terms
- any (type) — The TypeScript type that switches off type checking for a value, so anything can be done with it without errors.
- top type — A type that every other type fits into, so it can hold any value; in TypeScript both unknown and any play this role.
- type narrowing — The compiler refining a broad type to a more specific one inside a block, after a check proves which case applies.
- runtime validation — Checking real data with JavaScript code while the program runs, so values from outside are proven correct before they are trusted.
Taught in
- Literal Types: String, Number, Boolean Literals And const — Production TypeScript
- any Versus unknown: Defensive Typing In Practice — Production TypeScript
- never: The Bottom Type And Exhaustive Switch Checking — Production TypeScript
- Optional Properties, Readonly And Index Signatures — Production TypeScript
- The in Operator And Instanceof Narrowing — Production TypeScript
- Custom Type Predicates: Functions Returning is Type — Production TypeScript
- Generic Constraints: extends, keyof And Indexed Access — Production TypeScript