Reputation: 1527
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
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