TypeScript: any vs. unknown

TypeScript has some abstract types that can be helpful in Angular applications. Most people have encountered the type any at some point, and it has become a typical anti-pattern in several projects where developers decided: “I don’t want to bother using proper types for this object, so I’ll use any.

Here is why any is dangerous and not recommended:

Now, if we replace any with unknown, things look different:

As you can see, unknown preserves type safety. If we receive an object from a third-party library and need to pass it around to another function, unknown is perfect for that.

One way to think about unknown is: We have this object that we don’t know what’s inside, so we won’t allow touching it; we’ll store it or pass it around.

I can’t think of good reasons why we would need to use any in Angular code at this point. Using any is refusing to use TypeScript properly and falling back to untyped JavaScript.

In the next few days, we’ll cover different techniques and tools we can use to create accurate type information so we don’t need any or unknown anymore.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.