HobojoeBr
HobojoeBr

Reputation: 619

Jquery Promises Chaining + Typescript = Type Mismatch

I'm having some difficulties on TS while trying to chain jQuery Promises with .then

See my code below:

function first(): JQueryPromise<string>
{
    return $.when('1');
}

function test()
{
    $.when()
        .then(() =>
        {
            return first();
        })
        .then((value) =>
        {
            var str: string = value; //<--- type mismatch here.
        });
}

Typescript is expecting that value is of type JQueryPromise instead of "string".

If I cast value to any, I am able to make it work.

Is there a different way to implement it, or is there an error with JQuery definition file?

Thanks

Upvotes: 4

Views: 1445

Answers (1)

WorldMaker
WorldMaker

Reputation: 129

JQuery promises have a complicated structure in the DefinitelyTyped definition file, for the reason that JQuery promises themselves have a complicated structure/history. You should be able to help the compiler choose the correct overload by providing the generic argument, rather than relying on inference:

.then<string>(() =>
{
    return first();
})

Also, if you have a lot of work you need to do with promises, I do humbly like to suggest using a library like Q.js. Q is closer to the Promises/A+ specification that is the basis for ES6 promises, it's a simpler defined library so type inferencing tends to work better in TypeScript, and it provides a bunch of useful helper tools like Q.all.

Upvotes: 1

Related Questions