DEV Community

Lucas Paganini
Lucas Paganini

Posted on • Originally published at lucaspaganini.com

2 2

Unknown vs Any in TypeScript

Unknown vs Any in TypeScript with examples


See this and many other articles at lucaspaganini.com

Type Safety

unknown is the type-safe counterpart of any.

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

// Using any
const value: any = 'abc';
value.trim();
Enter fullscreen mode Exit fullscreen mode

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

// Using unknown
const value: unknown = 'abc';
value.trim();
Enter fullscreen mode Exit fullscreen mode

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

// Using unknown
const value: unknown = 'abc';
if (typeof value === 'string') {
  value.trim();
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

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!

References

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay