TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Generics allows erroneous type casting

Open jeremyhallden opened this issue 11 years ago • 4 comments

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;
    }
}

jeremyhallden avatar Jul 07 '15 13:07 jeremyhallden

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.

qc00 avatar Jul 07 '15 14:07 qc00

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.

RyanCavanaugh avatar Jul 07 '15 15:07 RyanCavanaugh

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 :)

jeremyhallden avatar Jul 09 '15 12:07 jeremyhallden

(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.

qc00 avatar Jul 09 '15 13:07 qc00