|
Hi everyone,
Something that immediately bit me and confused me about TypeScript is that a value with the Any type can be assigned into a variable that has been statically typed more specifically than 'Any'. E.g.
var a : any = {};
var s : string = a; // expected this to be an error
I found this out through a more complicated example where I had fields which were accidentally of the 'any' type (because the compiler couldn't infer anything stronger). The other way makes sense to me, the a variable should be able to hold a string. The
language specification does describe this behaviour:
"A type S is assignable to a type T, and T is assignable from S, if one of the following is true: ... S or T is the Any type."
But doesn't give an explanation as to why this is a desirable feature to have in the language. My gut feeling is that it has something to do with staying a strict superset of JavaScript, but currently I can't see why some sort of explicit cast shouldn't
be required in my example above, as is the case when casting from a super type to a base type:
class Animal {
}
class Snake extends Animal {
}
var a : Animal = new Animal();
var s : <Snake> = a; // type assertion allows this
s = a; // no type assertion, get error that cannot convert Animal to Snake
One thing I've found that at least discusses this behaviour is: http://siek.blogspot.co.uk/2012/10/is-typescript-gradually-typed-part-1.html
Could anyone enlighten me with an example as to why it is desirable for Any to be assignable to a statically typed variable?
|