Unknown vs Any in TypeScript

With examples

LinkType Safety

unknown is the type-safe counterpart of any.

While any says: "this can be anything, do whatever you want with it"

TypeScript
// Using any
const value: any = 'abc';
value.trim();

unknown says: "this can be anything, check what it is before using it"

TypeScript
// Using unknown
const value: unknown = 'abc';
value.trim();

This forces the developer to use type guards to safely narrow the type before performing any operations, thus ensuring type safety.

TypeScript
// Using unknown
const value: unknown = 'abc';
if (typeof value === 'string') {
  value.trim();
}

LinkConclusion

References are below.

This article is part of my TypeScript Narrowing Series, where we go from fundamentals to advanced use cases. You can read the full series for free here.

Have a great day, and I'll see you soon!

LinkReferences

  1. TypeScript Docs
  2. unknown vs any on Stack Overflow

Join our Newsletter and be the first to know when I launch a course, post a video or write an article.

This field is required
This field is required