Aref Zamani
Aref Zamani

Reputation: 2062

Why I need any type in typescript?

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

Answers (2)

Madara's Ghost
Madara's Ghost

Reputation: 174967

In your particular case, it doesn't matter. But

  • If you have the strict flag on (or, by extension, the noImplicitAny flag), it will throw an error for the first, but not the second. Because an implicit any is not allowed.
  • The reason they are the same is because TypeScript can't infer the type of the argument or the return type, so they are both inferred to any.

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 anys, implicit or explicit, because then you lose some of the benefit that TypeScript affords.

Upvotes: 1

Haytam
Haytam

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

Related Questions