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

Angular2: Learn how to dynamically create input fields when a button is clicked

My current challenge involves replicating input fields on click of a button. I have a set of input fields where data can be entered, and then I need to add another set of the same fields for additional data. There needs to be a way to remove these replicat ...

development response in jQuery

As a newcomer to jQuery, I am trying to understand the distinction between response and response.d. Currently, I am utilizing response.d for failure alerts. I am curious to know what message would be displayed in the alert box if there is a failure (alert ...

Step-by-step guide to adding a skew overlay to your video

I am experimenting with creating a skewed overlay on a video playing in the background at full width. Currently, the skew overlay is functioning perfectly. What if I want it to appear in the bottom-right corner instead of the top-left corner? Would I need ...

Is AJAX not submitting properly?

Here is the code snippet that I am working with: var just = $("#just").val(); var id = $("#id").val(); $.ajax({ type: "POST", url: "cod_ajax/just.php", data: "id="+id+"&just="+just, cache: false, success:function(e){ aler ...

I prefer to disable the toggle feature if the target remains unchanged

My goal is to create a step-by-step ordering system using the data-id="x" attribute to determine which content should be visible when selected. I want to make sure that if two elements have the same data-id, clicking on one will deselect the other. Any su ...

Arranging HTML elements with jQuery - the existing script flips back and forth

I have created a code snippet on CodePen that showcases a feature of the website I am currently developing: http://codepen.io/barrychapman/pen/BzJGbg?editors=1010 Upon loading the page, you will notice 6 boxes. The first box is active, while the remaining ...

Changing the sliding underline effect in a jQuery navigation bar

Recently, I implemented a sliding underline element in my navigation bar. The idea is that when a link is hovered over, the underline smoothly transitions to that element. You can take a look at the codepen example here: https://codepen.io/lucasengnz/pen/e ...

What is the best way to dynamically alter HTML elements on my webpage?

I have a selection of radio buttons on my webpage: <form ...> <input type="radio" name="people" checked> Member <input type="radio" name="people"> Manager <input type="radio" name="people"> Supervisor <!-- Here is t ...

Transforming an array of HashMaps into a JSON object within a servlet and showcasing it on a JSP page

Looking to extract all table rows and store them in an array of hashmaps, then convert them into a JSON object to be sent to a JSP page using Ajax and jQuery. Struggling with displaying the content on the JSP page. I've written the code below but need ...

How to inject a regular class in Angular2 without the @Injectable decorator

angular: 2.0.0-beta.9 Can we inject a non-@Injectable class into a component? For instance, if this class originates from an external Third party library. ...

How can I implement a pause in my JavaScript code?

Below is a snippet of code that I am using in my project: $.ajax({ url: $form.attr('action'), dataType: 'json', type: 'POST', data: $form.serializeArray(), success: function (json, textStatus, XMLHttpRequest) { ...

HTML background image not displaying in JSPDF addHTML function

I am facing an issue with my HTML page where the background image in the header section is not displaying when converting the page to PDF using jspdf. Although all the other content appears correctly, the background image seems to be missing. You can vie ...

Interactive 3D model movable within designated area | R3F

I am currently facing a challenge in limiting the drag area of my 3D models to the floor within my FinalRoom.glb model. After converting it to tsx using gltfjsx, I obtained the following code: import * as THREE from "three"; import React, { useRe ...

Troubleshooting: Resolving JSX props issue in Vue template

Ever since integrating the FullCalendar library into my Vue project, I've been encountering an error every time I try to use my custom component in a Vue template. My setup includes Vue 3, Vite, VSCode, eslint, and prettier. This issue seems to be m ...

Creating a web application that uses AJAX and smoothly degrades if the browser does not support JavaScript

Apologies for the lengthy title, but my main focus is on creating an ajax-based application. I currently have a version one of this app that operates without requiring javascript. I am looking to upgrade it to utilize ajax for accessing resources from a t ...

Managing two variables in C# Controller and View

I am facing an issue with the two variables in my controller class. The first variable, currentUserId, is supposed to store the user currently logged into the website. The second variable, currentRoomId, should track the chat room the user is in. The probl ...

An AJAX event handling function returns a null value upon invocation

Recently, I've been working on a function named 'getAuthor' which includes an AJAX event. Here's the code snippet: function getAuthor(id){ $.get('http://www.connectnigeria.com/articles/wp-json/wp/v2/users/74',function(e){ ...

I noticed that my WordPress website is loading both jQuery Migrate and jQuery version 1.10.2. Can you explain the difference between the two versions?

As I'm reviewing site performance checklists, I've observed that my WordPress website is loading both jQuery-migrate and jQuery 1.10.2. Is it necessary to have both, and what distinguishes them? ...

avoid triggering the on hover state

When working with jQuery, I have a CSS style targeting a specific div: div.right-sm:hover{background-color: blue} Now, I am trying to prevent the hover effect using jQuery: $(this).parent('div').removeClass('right-sm:hover'); Howev ...

An error occurred: [object Object] does not contain the function 'bootstrapDatepicker'

After spending countless hours searching for a solution, I continue to encounter the dreaded 'Uncaught TypeError' without any successful resolutions. The issue seems to stem from a clash between tribe-events-ajax-calendar.js and foundation.min.j ...