MBeckius
MBeckius

Reputation: 1527

type checking seems to be subverted

function test(parm : number) {
    console.log(parm);
}

var x = '12';
test(x); //does not compile as expected.
test(<any>x); //no error or warning.  

Why do I not get a compiler error on the last line? Any reference to the docs would be helpful.

TIA

Upvotes: 0

Views: 72

Answers (2)

Alexander R
Alexander R

Reputation: 2476

With <any>x what you're doing is casting the variable x to type any. That is, you're telling the compiler "Hey, in this place, I know that x is really of type any!". The compiler assumes you're right and uses the new type you've given it for that call.

any is a special type in TypeScript - it means that the type could be anything and could even change types! For this reason, the compiler allows variables of type any to be used instead of any other type. So, while your function only accepts a parameter of type number, it will also accept a parameter of type any, because, of course, that any could really be a number.

This behaviour is shown in the language specification in Section 3.8.4 - Assignment Compatibility (pages 44-45):

Types are required to be assignment compatible in certain circumstances, such as expression and variable types in assignment statements and argument and parameter types in function calls. S is assignable to a type T, and T is assignable from S, if one of the following is true...:

  • S and T are identical types.
  • S or T is the Any type.
  • ...

(emphasis mine)

Upvotes: 2

PM 77-1
PM 77-1

Reputation: 13344

OK. Directly from the specs (on page 23):

All types in TypeScript are subtypes of a single top type called the Any type.

So you're in place of type numeric you're using its supertype any. No conflict.

Upvotes: 2

Related Questions