Denis
Denis

Reputation: 133

jquery promise and typescript

Got the project from other developers, they have it correctly compiled, I have a bug in typescript on line "return deferred.promise()".

Type 'JQueryPromise<{}>' is not assignable to type 'JQueryPromise'.

export function promise<T>(resolver: (resolve: (data: T) => void, reject: (error: any) => void) => void): JQueryPromise<T> {
    const deferred = $.Deferred();
    resolver(
        data => {
            deferred.resolve(data);
        },
        ex => {
            deferred.reject(ex);
        }
    );
    return deferred.promise();
}

there are a lot of such errors, so I think the problem is not in the code but in some configuration, what could be the matter?

Upvotes: 3

Views: 2624

Answers (2)

TomEberhard
TomEberhard

Reputation: 1091

For code that doesn't use generics, I had almost the same error message, but instead of

Type 'JQueryPromise<{}>' is not assignable to type 'JQueryPromise'

it said

Type 'JQueryPromise<{}>' is not assignable to type 'IAccountSettings'.

where IAccountSettings is obviously my type, or in this case, an interface. Building on Cerberus' excellent answer above, I changed the declaration of the deferred by just putting in the specific type:

public get(): JQueryPromise<IAccountSettings> {
var deferred = $.Deferred<IAccountSettings>();

Upvotes: 0

Cerberus
Cerberus

Reputation: 10237

It seems that you just need to pass the proper type to the Deferred factory. This code compiles:

export function promise<T>(resolver: (resolve: (data: T) => void, reject: (error: any) => void) => void): JQueryPromise<T> {
    const deferred = $.Deferred<T>(); // here we used generic type for Deferred
    resolver(
        data => {
            deferred.resolve(data);
        },
        ex => {
            deferred.reject(ex);
        }
    );
    return deferred.promise();
}

I can't be sure, although, whether this problem is interfering with .NET specifics.

Upvotes: 4

Related Questions