Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"any" in Typescript

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

  1. var num:any = 12

  2. var num = 12

we could probably use the second one itself, what's the need for 'any'?

like image 376
Chinniah Annamalai Avatar asked Jun 15 '18 12:06

Chinniah Annamalai


People also ask

Can I use any in TypeScript?

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.

Is any a type in TypeScript?

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.

What is any [] in TypeScript?

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.

What is any [] in angular?

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.


2 Answers

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.

like image 139
Attersson Avatar answered Oct 13 '22 21:10

Attersson


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

like image 9
Sh. Pavel Avatar answered Oct 13 '22 22:10

Sh. Pavel