TypeScript Reference ยท Primitive and Special Types
The TypeScript unknown type
Reference for unknown in TypeScript: assignability, narrowing with typeof, instanceof and type guards, unknown versus any, catch variables and validation.
unknown is the type-safe counterpart of any. Every value can be assigned to unknown, but you cannot do anything with an unknown value until you have narrowed it to something more specific. It is the right type for data whose shape you have not verified: parsed JSON, catch variables, message payloads, function arguments from outside.
The compiler demands a check (typeof, instanceof, a type predicate, or a validation library) before you read properties or call methods.
let input: unknown = JSON.parse("[1,2,3]"); if (Array.isArray(input)) { console.log(input.length); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
let u: unknown; function handle(input: unknown): void {} const result = value as string; // assertion from unknown is allowed
Operation on unknown |
Allowed? |
|---|---|
| Assign any value to it | Yes. |
Assign it to unknown or any |
Yes. |
| Assign it to any other type | No, without narrowing or an assertion. |
| Property access, call, arithmetic | No (error TS18046 "'x' is of type 'unknown'"). |
===, !==, typeof, instanceof, in |
Yes, and these narrow it. |
Usage notes
- Top type.
unknownis at the top of the type hierarchy: everything is assignable to it.neveris at the bottom. - Unions and intersections.
T | unknownisunknown;T & unknownisT. - Index access. Narrow to
objectandinfirst:"name" in valuenarrowsvaluetoobject & Record<"name", unknown>. - Assertions are unchecked.
value as Pointcompiles but verifies nothing. Use a type guard or a schema validator for external data. catch (error)isunknownunderstrict(useUnknownInCatchVariables); checkerror instanceof Errorbefore reading.message.- Generic defaults. Write
function parse<T = unknown>(...)rather than defaulting toany. - Use it for JSON input,
postMessageevents, plugin hooks,Promise.rejectreasons and wrapper functions that pass values through untouched. - Comparison with
{}andobject: they excludenull/undefined(and primitives, forobject) whileunknownincludes everything.