Extended Type Inference

Topics: Language Specification
Apr 2, 2013 at 10:17 PM
Hi,

I've been working on strong typing for some asynchronous methods (promise type objects) for my codebase. I've managed to do this, but, it's rather code heavy since I have to redeclare quite a few methods for each derived class in order to override their returned types. So, this case comes to mind:
class A {
    result: any;
    getResult() {
        return this.result;
    }
    // More code that uses result.
}

class B extends A {
    result: string;
    // More code that uses result.
}

var a = new A();
var ar = a.getResult(); // Inferenced type: any. Real type: any.

var b = new B();
var br = b.getResult(); // Inferenced type: any. Real type: string.
Both variable ar and br are inferenced to have type any. However, I think it should be possible to inference that class B's .getResult() will return a string instead.

Understandibly, in a real runtime language doing this kind of inference would blow up the virtual method table sizes - but, since TypeScript is a compile-time-only language, overloading the VMTs shouldn't be a big issue.

Thoughts?
Coordinator
Apr 3, 2013 at 3:45 PM
There are cases like this we can offer better type information in the future, and I suspect we'll work to continue to improve the information we give you. The language spec is settling down for the 1.0 release, but this might be a good suggestion for post-1.0.
Apr 3, 2013 at 3:46 PM
IT would be really neat for the type inferencer to re-infer all superclass methods for each child with what it knows about the child. Having said that, I think overriding/shadowing properties is an anti-pattern. When generics are available in 0.9.x, I'd imagine the following would work well:
class A<T> {
    result: T;
    getResult() {
        return this.result;
    }
}

class B extends A<string> {
}
Apr 4, 2013 at 12:52 AM
@jonturner: Awesome, thanks!
@cretz: Didn't know generics were coming so soon - very cool! I think you're right and they would solve this issue as well.