Type Inference Problem

Topics: General
Jul 3, 2014 at 2:18 AM

I have a problem with Type Inference and I am not entirely sure if this is intentional or a bug:

If the line with instance in the Required class is uncommented it works. If the line is not there the result2 line in Test.test() has an error:
module Test {

    class Base {
        baseMember: number;

    class Derived extends Base {
        derivedMember: number;

    class Required<T extends Base> {
        someMember: number;
        //instance: T; //<<< result2 line only works if this is uncommented

    class ExtendedRequired extends Required<Derived> {
        someOtherMember: number;

    class Test {
        func<T extends  Base>(arg: Required<T>): T {
            return null;

        test(): void {
            var instance = new Required<Derived>();
            var result = this.func(instance).derivedMember;

            var instance2 = new ExtendedRequired();
            var result2 = this.func(instance2).derivedMember;
Jul 3, 2014 at 5:45 AM
Type inference in TypeScript works structurally, just like the rest of the type system. When inferring a type, the compiler (usually) relates members of the candidate types to determine generic type parameters. What this means is that if you have a class with a type parameter that isn't used, it's as if the type parameter simply didn't exist (for the purposes of inference).

Put more simply, do not have unused type parameters. In a more perfect world, this might be a compile error because it's so rarely the correct thing to do.