Reputation: 2062
We have a simple method in typescript
function identity(arg) {
return arg;
}
This method gives a parameter and returns it and it will work by any type (int,string,bool and more). We can also declare this method in another way:
function identity(arg:any):any {
return arg;
}
This method gives a parameter and returns it and it will work by any type (int,string,bool and more).
What is the difference between the two ways? In other word what is benefit using of any
type?
Upvotes: 0
Views: 84
Reputation: 174967
In your particular case, it doesn't matter. But
Any is your escape hatch from TypeScript, it means "I don't know what type this is, so anything I do with it is acceptable, any property on it implicitly exists (and also has a type of any), I can call it with any parameters, and I can also new
it.
It is recommended that you minimize your use of any
s, implicit or explicit, because then you lose some of the benefit that TypeScript affords.
Upvotes: 1
Reputation: 4733
any
is like an anonymous type, not like Object
. When using any
, the compiler does minimal type checking since it doesn't know your variable's members.
Example:
var var1: any;
var var2: Object;
var1.whatever(); // The compiler trusts you
var2.whatever(); // Compiler throws an error
As you can see in the example, you can handle var1
however you want, but you can't mess with var2
except for its official members.
In your function, you can whatever you want with your arg
, but if you specify a type for it then you'll be bound to use that type's members.
Upvotes: 0