The "any" type in Typescript - simple and short explanation
Arika O
Posted on May 29, 2020
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:
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:
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
Posted on May 29, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.