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