Any type is the base type for all other types in TypeScript. Any type can represent any value with no constraints. The TypeScript compiler does not perform type checking on Any type. Any variable can hold anything like primitives, objects, arrays, functions, errors, symbols, etc.
Table of Contents
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 var1
and var2
as of type Any.
1 2 3 4 | 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 anyvar
variable.
1 2 3 4 5 6 7 | let anyVar:any anyVar="100.5175"; anyVar={} anyVar=100.51575; console.log(anyVar.toFixed(2)); |
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
1 2 3 4 5 | let anyVar:any anyVar={} 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 third-party libraries and does not want the compiler to throw errors
Existing JavaScript
When you port your existing JavaScript code. You can make use of any type until you migrate the program to typescript.