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).

GroupBasic Types
KindType
Strict modeNot 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.
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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏