Table of Content
Declaring Any Type
The typescript creates a variable as Any under the following circumstances
- If you do not declare the type and typescript does not infer the type from its initialization or from its usage (inferred typing).
- You explicitly declare the type as Any (explicit typing)
For Example, Typescript creates the variables
var2 as of type Any.
let var1; //inferred typing
let var2:any //explicit typing
No Type Checking
The Typescript compiler does not make type checking on the variable of type Any. When you define a variable as Any, you are basically opting out of type checking. For Example, the following code compiles & runs without any issue. Although we assign string, object, and number to the
The following code also compiles although the
toFixed method does not exist on
object. But when you run the code you will get the following error.
TypeError: anyVar.toFixed is not a function
console.log(anyVar.toFixed(2)); //TypeError: anyVar.toFixed is not a function
When to use Any
You should avoid using Any as you will lose the benefit of the type checking. The type errors occur only at runtime and that is against one of the main reasons why use TypeScript.
But there are many scenarios where you may not know the type of the variable. The following are two such scenarios, where using Any makes sense.
When working with third party libraries
You can use Any when you do not know the data type of the variable. This may be the case when you work with the third-party libraries and does not want the compiler to throw errors