Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 29, 2020 10:37 pm GMT

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


Original Link: https://dev.to/cilvako/the-any-type-in-typescript-simple-and-short-explanation-457j

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To