Unknown vs. Any in TypeScript

Unknown vs. Any in TypeScript

1月 12, 2020 · 1 分钟阅读时长 · 115 字 · -阅读 -评论

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

Alan H
Authors
开发者,数码产品爱好者,喜欢折腾,喜欢分享,喜欢开源