Unknown vs. Any in TypeScript

Highlights the core difference between unknown and any, with examples of type narrowing and why unknown is safer.

Jan 12, 2020 · 1 min read · 115 Words · -Views -Comments · Programming
TypeScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

For a full deep dive on unknown, see the recommended article below. This post just clarifies the key difference between unknown and any.

any is the top type but sacrifices safety—once you use it, the compiler stops helping. unknown exists to fix that.

any = no type safety. unknown = must narrow before use.

comparison 1
comparison 2

If the compiler can’t guarantee a is a number, it won’t let you call .toString() on unknown. any would allow it.

With unknown, you must perform your own type checks before manipulating the value.

Type Guards

type guard screenshot

Notice the return type value is number instead of boolean. That tells TypeScript the check narrows the type:

narrowing result

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover