Unknown vs. Any in TypeScript
·
1 min read
·
115
Words
·
-Views
-Comments
For a full deep dive on
unknown
, see the recommended article below. This post just clarifies the key difference betweenunknown
andany
.
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.
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
Notice the return type value is number
instead of boolean
. That tells TypeScript the check narrows the type: