unknown The unknown Type
Last updated: 2026-10-22
unknown The unknown Type
unknown is the safe any: any value is assignable to it, but it must be narrowed or asserted before use. The go-to type for external input (API responses, JSON.parse results).
| Group | Basic Types |
|---|---|
| Kind | Type |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
let value: unknown = JSON.parse(text);
if (typeof value === "string") {
value.trim(); // method calls only after narrowing
}
⚙️ Parameters
| typeof x === "string" | Checks like typeof x === "string" narrow unknown to a concrete type |
|---|
Returns:None — unknown is a type annotation and produces no runtime code.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
hi
2.5
unsupported
(Runtime output after transpilation; calling value.trim() without narrowing is a compile error — that is unknown's protection)
💡 Notes
ℹ️ Info Assignability is the key difference: unknown only flows into unknown/any, while any flows everywhere — so unknown cannot spread unsafety.
💡 Tip Common narrowing tools: typeof (primitives), instanceof (class instances), in (property presence), Array.isArray.
⚠️ Note Narrowing proves the type assumption, not the data's shape; validate external JSON with a schema library like zod.
🏷️ Related Basic Types
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q Should I choose unknown or any?
A Default to unknown: it forces you to confirm the type before use, surfacing errors at compile time. any is a temporary tool for prototyping or migrating legacy code.
Q How do I turn unknown into a concrete type?
A Two ways: narrowing (typeof/instanceof/in, tracked automatically) or an assertion value as T (you vouch for it). Prefer narrowing; assert sparingly.
Q What does JSON.parse return?
A The lib signature says any. Safer to wrap: function safeParse(text: string): unknown { return JSON.parse(text); } and validate with a schema.