I am beginner in typescript. I have a doubt in usage of "any" type.
Using "any" is basically opting out type checking if I am right. For example
var num:any = 12
var num = 12
we could probably use the second one itself, what's the need for 'any'?
any. ❌ Don't use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.
Any is a data type in TypeScript. Any type is used when we deal with third-party programs and expect any variable but we don't know the exact type of variable. Any data type is used because it helps in opt-in and opt-out of type checking during compilation.
Types Array<any> and any[] are identical and both refer to arrays with variable/dynamic size. Typescript 3.0 introduced Tuples, which are like arrays with fixed/static size, but not really.
It is a two part declaration - [] is used in Typescript to declare an array of values. The any is used to declare that the entries in the array can be of any type.
While the two are equivalent in use (because any
is the default type when unspecified) by explicitly specifying the type as any
, you explicitly declare the intent.
Intellisense, where available, will display the type as any
, allowing easier understanding how your variable is meant to be used.
First of all - If we speak about Typescript, lets avoid the var key-word.
We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content, e.g. from the user or a 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the any type:
Example to this:
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
More: Types in Typescript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With