Generic Type Inference Issue

Topics: General
Apr 24, 2014 at 10:48 PM

I'm having an issue with the latest version of TypeScript where the generic type inference is not working as I would expect it to. I believe that this use to work in the previous release version of TypeScript.

Basically, I have a method with a generic parameter that should be inferable based on an input argument, and then used as a return type.

See the "requestResource" method below:
interface IHttpPromiseCallback<T> {
    (data: T): void;

interface IHttpPromise<T> {
    success(callback: IHttpPromiseCallback<T>): IHttpPromise<T>;
    error(callback: IHttpPromiseCallback<T>): IHttpPromise<T>;

interface IRequestEx<TResponse> { }

interface ILogRep {
    message: string;

interface ICreateLogRequestEx extends IRequestEx<ILogRep> { }

class TestClass {
    requestResource<TResponse>(request:IRequestEx<TResponse>): IHttpPromise<TResponse> {
        return null;
    test() {
        var request: ICreateLogRequestEx;
        var response = this.requestResource(request);   
        // Note that "response" is inferred to be IHttpPromise<{}> and not IHttpPromise<ILogRep>
        // !!! This SHOULD work ??   logRep should be inferred to be a ILogRep
        response.success((logRep) => console.warn(logRep.message));

        // WORKAROUND #1: add type information to callback parameter
        response.success((logRep: ILogRep) => console.warn(logRep.message));
        // WORKAROUND #2: explicitly specify type in 'requestResource' call
        var response2 = this.requestResource<ILogRep>(request);
        response2.success((logRep) => console.warn(logRep.message));
Please let me know what (if anything) I'm doing wrong here.


Apr 25, 2014 at 12:31 AM
Edited Apr 25, 2014 at 1:13 AM
That's because "IRequestEx<TResponse>" is missing a member. Add "r: TResponse;" to it and it will work. Someone else already posted something on this as well. Empty interfaces should work in my opinion, but unfortunately you must define at least one member in order for type inference to work.
Apr 25, 2014 at 5:42 AM
Sweet, that did fix it! Thanks.

Totally agree that empty interfaces should be supported.