12

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?

1 Answer 1

9

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Even though I now understand how this works, I still find it strange. Even without the --noImplicitAny option I would presume that when I add a type to a function declaration then it will require any caller to pass that type. The meaning of any should still be "this can be anything", but you shouldn't just pass an "anything" variable somewhere where a specific type is required.
@LukasH I see you've programmed in c#. The any type currently works like a dynamic variable in c# (ex. dynamic str = "asdf"; int num = str; is ok). So like how you should avoid dynamic types in c#, I would recommend avoiding any types in TypeScript.
I understand your point, but it's hard to avoid any when you're converting existing javascript project to typescript. For this kind of workflow turning on --noImplicitAny is not an option as it would need a rewrite of the whole code base. The any I would like to have is an object that can have any properties, but you can't pass it anywhere where a certain type is requested.
@LukasH I opened up this github issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.