teckno.query teckno.query - 2 months ago 25
TypeScript Question

TypeScript: error TS2345: Argument of type 'JQueryXHR' is not assignable to parameter of type 'Promise<any>'

The following example code snippet is presented in a tutorial on how to perform a JQuery getJSON() call and then convert the JQueryXHR result to a Promise, which is then converted to an 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);
}
}


This example does work at runtime, but the tsc compiler throws the following error:

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.


Is there a clean way to cast or convert a JQueryXHR object to a Promise, or another type, that can be converted to an Observable?

Answer

Is there a clean way to cast or convert a JQueryXHR object to a Promise?

You're looking for Promise.resolve which does exactly that.

However, your current code should work already if only the types would be more precise. fromPromise should not require a Promise but only a Thenable, and JQueryXHR should implement the Thenable interface.

Comments