The "any" type in Typescript - simple and short explanation

arikaturika

Arika O

Posted on May 29, 2020

The "any" type in Typescript - simple and short explanation

Probably one of the most debated types in Typescript is the any type. Some abuse it, some tell you to use it as little as possible. How does this work?

Imagine that we need to specify the type of a variable but we don't know exactly what that variable will hold when writing our code. These values may be dynamic (they might come from a 3rd party library, for example). In this case, the best approach would be not to check the type of the variable (half true, since we'are actually using a type to specify that we expect whatever and we're fine with it). We can do so by using the any type and let the variables to be dealt with at compile time. The any type doesn't look any different from the others and we write it like this:

Alt Text

This is also very useful when we work with arrays and we don't know the types of all its elements. To avoid issues we can do something like this:

Alt Text

Notice that in the first example, I specified I want an array of type number so when trying to push a string to it, I got an error. The second example passes successfully.

Image source: Christina Morillo/ @divinetechygirl on Pexels

πŸ’– πŸ’ͺ πŸ™… 🚩
arikaturika
Arika O

Posted on May 29, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Getting Started with Typescript
typescript Getting Started with Typescript

July 21, 2024

Classes in TypeScript: With Challenges
keyof typeof Object
typescript keyof typeof Object

June 10, 2023

Part 6: Advanced TypeScript Topics
typescript Part 6: Advanced TypeScript Topics

May 23, 2023