简体   繁体   English

Jquery承诺链接+ Typescript =类型不匹配

[英]Jquery Promises Chaining + Typescript = Type Mismatch

I'm having some difficulties on TS while trying to chain jQuery Promises with .then 在尝试使用.then链接jQuery Promise时,我在TS上遇到了一些困难

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". Typescript期望该值的类型为JQueryPromise而不是“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? 是否有不同的方法来实现它,或者JQuery定义文件是否有错误?

Thanks 谢谢

JQuery promises have a complicated structure in the DefinitelyTyped definition file, for the reason that JQuery promises themselves have a complicated structure/history. JQuery promises在DefinitelyTyped定义文件中有一个复杂的结构,因为JQuery承诺自己有一个复杂的结构/历史。 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.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 . Q更接近作为ES6承诺基础的Promises / A +规范,它是一个更简单的定义库,因此类型推断往往在TypeScript中更好地工作,并且它提供了许多有用的辅助工具,如Q.all

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM