DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Lucas Paganini
Lucas Paganini

Posted on • Originally published at lucaspaganini.com

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

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.