The TypeScript error code TS2345 indicates that the argument type 'JQueryXHR' cannot be assigned to the parameter type 'Promise<any>'

In a coding tutorial, an example code snippet demonstrates how to execute a JQuery getJSON() call and then transform the result into a Promise, which is later converted into 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);
  }
}

Although this example functions during runtime, the tsc compiler throws an error message:

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 way to cleanly cast or convert a JQueryXHR object into a Promise or another suitable type that can be transformed into an Observable?

Answer ā„–1

Is there a way to easily convert a JQueryXHR object into a Promise?

If you're looking for a solution, you can check out Promise.resolve which can help with that.

Your current code should be functional if the types are more specific. The function fromPromise does not necessarily need a Promise, but rather a Thenable, and ideally, the JQueryXHR should adhere to the Thenable interface.

Answer ā„–2

Solution (credit to @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 {
  performSearch(searchTerm: string) {
    let apiUrl: string =
      "https://api.spotify.com/v1/search?type=artist&q=" + searchTerm;
    let xhrRequest: JQueryXHR = $.getJSON(apiUrl);
    let promiseResult: Promise<any> = Promise.resolve(xhrRequest);
    let searchObservable = Observable.fromPromise(promiseResult);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing an issue of receiving an undefined value while attempting to retrieve a value from an input box

HTML: <input value='Rename' type='button' onclick='RenameGlobalPhase({$row['id']});' <span id='renameGlobalPhase{$row['id']}'>" . $row['phase'] . "</span> Below you wil ...

Ways to confirm the validation of radio buttons in a form and implement CSS

I am having trouble adding validation to a form with radio buttons displayed as labels. I want to show a red border around the radios/labels or outer div when a radio button hasn't been checked before the user submits the form. I have attempted this ...

How to efficiently retrieve individual values from input fields using jQuery AJAX while the inputs are within a foreach loop

In the world of PHP, input fields and delete buttons are magically generated by a foreach loop! To successfully extract the value from an input field and dispatch it to PHP, I rely on this code snippet: HTML: <input type="hidden" name="file_id" id="&l ...

Tips for retrieving sent data from a jQuery Ajax request on XHR error

I am facing a situation where I have numerous jQuery AJAX requests being sent using a single function. function sendData(data){ $.post("somepage", {"data": data}, function() {}, "json") .fail(function(jqXHR, textStatus, errorThrown){ sendD ...

Implementing NgRx state management to track and synchronize array updates

If you have multiple objects to add in ngrx state, how can you ensure they are all captured and kept in sync? For example, what if one user is associated with more than one task? Currently, when all tasks are returned, the store is updated twice. However, ...

How to extract the YouTube video source using jQuery from an iframe snippet

Currently, I am attempting to extract the YouTube source from an iframe embed code and store it as a variable. Suppose my YouTube embed code looks like this: <iframe width=&quot;1024&quot; height=&quot;576&quot; src=&quot;https://w ...

Is it possible to use an Enum as a type in TypeScript?

Previously, I utilized an enum as a type because the code below is valid: enum Test { A, B, } let a: Test = Test.A However, when using it as the type for React state, my IDE displays an error: Type FetchState is not assignable to type SetStateActi ...

Angular: Converting JSON responses from HttpClient requests into class instances

I am facing an issue with the following code: public fetchResults(searchTerm: string): Observable<Array<SearchResult>> { let params = new HttpParams().set('searchTerm', searchTerm); return this.http .get<Array< ...

The ability to submit a conversation chat is currently

I encountered an issue when attempting to submit a chat, and I received the error message 'handlebar is not define'. I followed the code tutorial provided in this link: https://codepen.io/drehimself/pen/KdXwxR This is the screenshot of the error ...

Exploring the inner workings of a JSON with Ajax and PHP

I'm working on a project that involves a JSON file called items.json. My goal is to create a search box where users can input either the name of an item or its category, and see live search results as they type. Here's what Iā€™m aiming for: If ...

When an input event is dispatched in a unit test, the value changes of a form are not activated

Currently, I am testing a scenario where I need to verify if a value changes on the form when input is typed in. This particular project utilizes Nrwl nx as well as jest for testing purposes. The component code snippet is as follows: export class InputNu ...

The SharePoint 2010 standard model dialogs seamlessly blend transparent printing with the background content

When using Sharepoint 2010, each list item you edit will open in a new modal dialog box by default. This dialog box appears as a new div with the class of ms-dlgContent. It also creates a div with the class of ms-dlgOverlay which acts as a grey overlay di ...

Styling Easy-Autocomplete with jQuery

I am currently working on integrating autocomplete functionality using the jquery easy-autocomplete plugin npm install --save easy-autocomplete I am facing two issues related to its styling. The results are being displayed in a bulleted list format. I ...

Transforming res.json() into an Array of Objects

I am dealing with a Java webservice that outputs a list of Json objects with specific properties: public class Oferta { private int id; private String categoria; private String descricao_oferta; private String anunciante; private double valor; private boo ...

Adding content to a div element using jQuery is a simple and effective way to

I am attempting to incorporate the content from a specific div into a jQuery function. Kindly refer to the details below: This is the content I want to include: <div id="year">2020</div> My objective is to replace the '2019' within ...

Customizing the HTMLElement class to modify particular attributes

Is there a way to modify the behavior of an HTMLElement's scrollTop property by adding some extra logic before updating the actual value? The common approach seems to be deleting the original property and using Object.defineProperty(): delete element. ...

Encountering a "Method Not Allowed" error when attempting to process a Laravel Stripejs

Seeking to integrate stripe payment into my laravel app, The stripe payment form I utilized can be found at, The HTML code used is as follows: <div class="container"> <div class='row'> <div class='col-md-4' ...

Every other attempt at an Ajax request seems to be successful

I'm new to using ajax and I'm having an issue with submitting a form through a post request. Strangely, the code I wrote only works every other time. The first time I submit the form, it goes through ajax successfully. However, on the second subm ...

Protecting String in PHP to Utilize in JavaScript

When I receive code through AJAX, I handle it as shown below: $verifiedSubject = addslashes(htmlentities($_REQUEST['subject'])); $verifiedBody = addslashes(htmlentities($_REQUEST['body'])); $verifiedAttachment1 = addslashes(htmlentitie ...

How to automatically collapse all opened accordion panes in jQuery when a new one is expanded

I am currently working on implementing an accordion feature that needs to collapse other expanded links when a new one is clicked. I am aware that this functionality is available in the accordion plugin, but I want to avoid adding another library like jQue ...