this typing in static method

Topics: General, Language Specification
Jan 24, 2014 at 1:26 AM
Edited Jan 24, 2014 at 1:29 AM
Since static method are inherited providing this typing contextually to the class could be cool:
class A {
    factory() {
        return new this();
    }
}

class B extends A {
}
var b = B.factory(); // b typed to B

going further typescript could even allow a special typeof this which could offer many Features.
class Base {
    private decorators: Decorator<typeof this>;

    constructor() {
        this.decorators =  this.constructor
            .decoratorClasses.map(decoratorClass => new decoratorClass(this));
    }
    
    private static decoratorClasses: {  
            new(instance: typeof this): Decorator<typeof this>;  
         }[];

    static decorate( decoratoClass { 
                new(instance: typeof this): Decorator<typeof this>; 
    }): void {
        decoratorClasses.push(decoratoClass)
    }
}

interface Decorator<T extends Base> {
    ///do something on instance
}

class MyClass extends Base {
    //some  methods
}
class MyClass2 extends Base {
    //some other incompatible methods
}
MyClass.decorate(....) // wil not accept Decorator<MyClass2>

seems a nice pattern :p
Coordinator
Jan 24, 2014 at 4:47 PM
Call me crazy, but your first example makes me think we have a bug in our typechecker. I altered it a bit and came up with this:
class A {
    bob() { alert("A"); }
    static factory() {
        return new this();
    }
}

class B extends A {
    bob() { alert("B"); }
}
var b = B.factory(); // b actually typed to A

b.bob();  // alert("B"), wait, what?
Jan 25, 2014 at 10:35 AM
Edited Jan 25, 2014 at 10:45 AM
Bug or not actually using 'this' in static methods then subclassing sure results in incoherent typing.
Should I transform it in an issue ?