【问题标题】:TypeScript: error TS2345: Argument of type 'JQueryXHR' is not assignable to parameter of type 'Promise<any>'TypeScript:错误 TS2345:“JQueryXHR”类型的参数不可分配给“Promise<any>”类型的参数
【发布时间】:2017-02-07 03:27:21
【问题描述】:

以下示例代码 sn-p 在教程中介绍了如何执行 JQuery getJSON() 调用,然后将 JQueryXHR 结果转换为 Promise,然后将其转换为 Observable。

/// <reference path="../typings/tsd.d.ts" />

import { Component } from '@angular/core';
import { Observable } from 'rxjs/Rx';

@Component({
    selector: 'my-app',
    template: `
        <input id="search" type="text" class="form-control">
    `
})
export class AppComponent {
  example(searchTerm: string) {
    let url: string =
      "https://api.spotify.com/v1/search?type=artist&q=" + searchTerm;
    let jqueryXhr: JQueryXHR = $.getJSON(url);
    let observable: Observable<any> = Observable.fromPromise(jqueryXhr);
  }
}

此示例在运行时确实有效,但 tsc 编译器会抛出以下错误:

app/app.component.ts(28,61): error TS2345: Argument of type 'JQueryXHR' is not assignable to parameter of type 'Promise<any>'.
  Types of property 'then' are incompatible.

有没有一种简洁的方法可以将 JQueryXHR 对象转换或转换为 Promise 或其他可以转换为 Observable 的类型?

【问题讨论】:

    标签: jquery typescript promise observable


    【解决方案1】:

    有没有一种简洁的方法可以将 JQueryXHR 对象转换或转换为 Promise?

    您正在寻找的 Promise.resolve 正是这样做的。

    但是,如果只有类型更精确,您当前的代码应该已经可以工作了。 fromPromise 不应该需要Promise,而只需要Thenable,并且JQueryXHR 应该实现Thenable 接口。

    【讨论】:

    • 根据错误,属性“then”的类型不兼容,导致使用隐式或显式转换时出错。但是,使用您对 Promise.resolve() 的建议有效,这让编译器感到满意。感谢您的回答。
    • 是的,这就是 thenables 和 promises 之间的区别——在后者中,then 方法的返回值及其回调很重要。
    【解决方案2】:

    回答(感谢@Bergi):

    /// <reference path="../typings/tsd.d.ts" />
    
    import { Component } from '@angular/core';
    import { Observable } from 'rxjs/Rx';
    
    @Component({
        selector: 'my-app',
        template: `
            <input id="search" type="text" class="form-control">
        `
    })
    export class AppComponent {
      example(searchTerm: string) {
        let url: string =
          "https://api.spotify.com/v1/search?type=artist&q=" + searchTerm;
        let jqueryXhr: JQueryXHR = $.getJSON(url);
        let promise: Promise<any> = Promise.resolve(jqueryXhr);
        let observable = Observable.fromPromise(promise);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-10
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 2019-09-07
      • 2018-02-09
      • 2022-11-21
      相关资源
      最近更新 更多