LukasH
LukasH

Reputation: 155

TypeScript typed function argument accepts any

Here is a TypeScript snippet that compiles just fine (using 1.5.3).

function alertNumber(a: number) {
    alert(a + 1);
}
var x:any = "string";
alertNumber(x);

How is it possible that a function requesting parameter of a certain type can be called with argument of type any?

Upvotes: 12

Views: 5249

Answers (1)

David Sherret
David Sherret

Reputation: 106640

It's because you opt out of type-checking when you use any types.

[Sometimes] 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. - Handbook

To avoid troubles with any:

  1. Use the --noImplicitAny compiler option (or turn off Allow implicit any types in Visual Studio).
  2. Don't use explicit any types except where necessary (Ex. var x: any)

Upvotes: 9

Related Questions