Generics allows erroneous type casting
Using generics, it seems as the TypeScript compiler fails to identify illegal type casts. See the code below, which should be self-explanatory. The convertSucceedsCore method allows you to convert anything without compiler warnings. This should only be possible if one uses an explicit any-cast.
Am I missing something here? :)
Thanks, Jérémy
interface IHelloer{
sayHello(): string;
}
class GoodByer{
public sayGoodBye(){ return "Goodbye"; }
}
class Main{
public convertFails(){
var helloer: IHelloer = null;
helloer = <IHelloer>(new GoodByer()); // fails correctly on compile
}
public convertSucceeds(){
var helloer: IHelloer = null;
helloer = this.convertSucceedsCore<IHelloer>(new GoodByer()); // succeeds - should not!
}
public convertSucceedsCore<T>(obj: Object) : T{
return <T>obj;
}
}
This is because <T>obj is a type assertion meaning you're saying to the compiler "I know better than you and the value must be this type here".
Your code has the same semantics as
var helloer: IHelloer = <IHelloer>(<Object> new GoodByer());
which is expected to compile.
To expand a bit, <T>x, where x is of type U, is allowed if T is assignable to U or vice versa.
Pretty much anything is assignable to Object, so the assertion in convertSucceedsCore always works.
If instead your method had been written:
public convertSucceedsCore<T, U>(obj: U): T {
return <T>obj;
}
You'd get an error there saying T is not assignable to U.
Thanks for the repsonses. I'm still not quite sure why
var helloer: IHelloer = <IHelloer>(<Object> new GoodByer());
is any different from
var helloer: IHelloer = <IHelloer>(new GoodByer());
since GoodByer is a subtype of Object?
Thankful for the help :)
(Please note markdown stripped the angle brackets, so I am guessing here.)
The TypeScript type checker tries to help you by rejecting obvious errors in type assertions, e.g. var x = <string> 1. However, if you remove enough information from the right-hand side of an assertion such that there is a possibility where the assertion is valid, then the compiler shuts up (in the hope that you've used the assertion correctly).
In the case of
var helloer: IHelloer = <IHelloer>(<Object> new GoodByer());
you've asked the compiler to only see new GoodByer() as Object type (regardless of the actual type) and it knows some Object can match the IHelloer interface, so it does not generate any errors.