×
☰ See All Chapters

TypeScript any type

As the name itself says, any type accepts value of any type and opts out of type checking for a variable; hence any data type is the super type of all types in TypeScript. Using any type is equivalent to a variable in javascript without any type. If we are receiving the value from 3rd party and if type of value is dynamically changing then we may need to describe the type of variables that we do not know when we are writing an application. In these cases, we want to opt-out of type-checking and let the any values be accepted during runtime. To do so, we declare these variables with the any type.

let anyTypeVariable: any = 10;

anyTypeVariable = "Hello";

anyTypeVariable = false; // value changed to boolean type

Using any type is similar to using Object type. But any type is powerful than Object type because any type helps to pass the compile time by when we call some functions on any type variable which might exists during runtime. As an example, in the below code we are calling isTrue() method over anyTypeVariable. This isTrue() function does not exists but we are sure isTrue() will be available during runtime. Hence we need to pass the compile time informing compiler to opt out to check the availability of isTrue() function on anyTypeVariable.

let anyTypeVariable: any = 10;

if (anyTypeVariable.isTrue()) {

       

}

 

 

Using Object type will not let you pass the compilation until isTrue() function is available during compile time too.

 typescript-any-type-0
 

The any type is also useful if you know some part of the type, but perhaps not all of it. For example, you may have an array but the array has a mix of different types and not all the types are known to create Tuple.

let list: any[] = ["Manu", 100, true ];

 

 


All Chapters
Author