Strange error message regarding ES6 promises that is difficult to interpret

Snippet

getToken(authCode: string): Promise<Token> {
    return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => {
        if (json["error"]) {
            return Promise.reject(json);
        }
        return new Token(json);
    });
}

Issue reported by Tsc(2.0.6):

xxx.ts(135,81): error TS2345: Argument of type '(json: any) => Promise<never> | Token' is not assignable to parameter of type '(value: any) > PromiseLike<never>'.                                                                  
  Type 'Promise<never> | Token' is not assignable to type 'PromiseLike<never>'.                                      
    Type 'Token' is not assignable to type 'PromiseLike<never>'.                                                     
      Property 'then' is missing in type 'Token'.

Configuration in Tsconfig.json:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "lib": [
            "es6",
            "dom"
        ]
    }
}

Note about promise typings being defined in

node_modules/typescript/lib/lib.es2015.iterable.d.ts


However, if the rejected Promise is not returned:

getToken(authCode: string): Promise<Token> {
    return fetch(tokenUrl, { method: "POST" }).then(res => res.json()).then(json => {
        return new Token(json);
    });
}

No errors occur in this case. How can a rejected promise be properly returned?

Answer №1

In this scenario, the rejected promise is not being returned; instead, an error is thrown to reject the promise:

receiveToken(authenticationCode: string): Promise<AuthenticationToken> {
    return fetch(tokenEndpoint, { method: "POST" }).then(response => response.json()).then(data => {
        if (data["error"]) {
            throw new CustomError(data["error"]);
        }

        return new AuthenticationToken(data);
    });
}

Answer №2

Apologies for jumping in on an older query, but I want to suggest incorporating Promise.resolve() around return new Token(json).

getToken(authCode: string): Promise<Token> {
  return fetch(tokenUrl, { method: "POST" })
    .then(res => res.json())
    .then(json => {
      if (json["error"]) {
        return Promise.reject(json);
      }
      // Make sure to do this
      return Promise.resolve(new Token(json));
    });
}

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

TypeScript encountered an error with code TS2554, indicating that it was expecting 0 arguments but instead received 1 in an Ionic application

Hello everyone! I'm encountering an issue in my project involving a Type Script error TS2554: Expected 0 arguments, but got 1. This error is preventing me from being able to select other options for custom input pop up. In this forum post, I have shar ...

Customizing Google Maps API v3: Utilizing Custom Images as symbolPath Instead of Default Symbols

Recently, I discovered the fascinating feature called Symbol Animation in Google API's documentation. All aspects of my code are functioning optimally; however, I am curious to know if it is possible to substitute an image for a symbol in the followi ...

Initiate the IE driver in WebDriver NodeJS with the option to disregard protected mode settings and possibly introduce flakiness

I'm attempting to create a driver session using IE capabilities to bypass protected mode settings in Internet Explorer, but I'm unsure of the correct syntax. I've experimented with the following: var driver = new webdriver.Builder().wi ...

Angular2 - receiving an error message stating that this.router.navigate does not exist as a

Currently, I am delving into the world of Angular2 with Ionic and working on crafting a login page. However, upon loading the page, an error surfaces: 'router.initialNavigation is not a function' To address this issue, I inserted '{initialN ...

Can you identify the reason for the hydration issue in my next.js project?

My ThreadCard.tsx component contains a LikeButton.tsx component, and the liked state of LikeButton.tsx should be unique for each logged-in user. I have successfully implemented the thread liking functionality in my app, but I encountered a hydration error, ...

searching backwards using regular expressions

I have successfully extracted <%? imagepath;%> using the following regex from a string. <%(\?|.|\s)*%> <img src="http://abc/xyz/<%? imagepath;%>.gif"> <img not_src="http://abc/xyz/<%? imagepath;%>.gif"> <i ...

Attempting to intercept a 401 error in an HTTP interceptor, I aim to refresh my session and then retry the initial request

My goal is to intercept responses returning from the /api, catching them if they are a 401 error, executing a refresh session action, and then retrying the original HTTP call again (while also preventing it from infinitely looping if another 401 error occu ...

"Transforming a callback function to an asynchronous function results in an error

I have a piece of code that is functioning as expected: var smtpConfig = { host: 'localhost', port: 465, secure: true, // use SSL selfSigned: true }; // create reusable transporter object using the default SMTP ...

Manipulate the value(s) of a multi-select form field

How can you effectively manage multiple selections in a form field like the one below and manipulate the selected options? <select class="items" multiple="multiple" size="5"> <option value="apple">apple</option> <option va ...

"Need help passing an API key in the header of a Vue.js project? I recently encountered this issue while using a

How can I include an API key in the header of a Vue.js request? I am using DRF pagination. methods: { getPostData() { axios .get("http://192.168.43.126:8000/api/?page=" + this.currentPage, { headers: { &q ...

Popup showing values that are not defined

I've encountered an issue with tooltips on my bar graph. The tooltips should display the values of boarding and alightings corresponding to each stopname column, but I'm seeing undefined values like this Below is my code snippet: <!DOCTY ...

Modifying linked dropdown selections with jQuery

I'm trying to create a recurrent functionality where I have 3 select elements. When the first select is changed, it should update the second and third selects accordingly. If the second select is changed, then it should also affect the third select. ...

UI-router issue: UI view and links not functioning properly

Recently, I decided to implement ui-router for Angular in my project. After adding the following code snippet to my app module within the app.js file: angular .module("ngClassifieds", ['ngMaterial', 'ui.router']) .config(function($md ...

Utilizing IonPage and DeepLinkMetadataType in Ionic 3 for tab navigation: Eliminating the need for tab-0

One of the pages on my site contains tabs that are only loaded when clicked: explore.html <ion-tabs> <ion-tab [root]="tab1Root" [tabTitle]="hotTitle" tabIcon="flame"></ion-tab> <ion-tab [root]="tab2Root" [tabTitle]="searchTitle ...

How do I retrieve the data returned from the component.ts file in Angular Material's MatTableModule when it is not directly inside the mat-table in the template?

I'm currently working on an Angular 5 project where I have integrated a table to display data using MatTableModule from angular material. This specific inquiry consists of two parts. Within my project, there is a service that sends a GET request to t ...

Is there a way to automatically generate additional text fields based on the user's input?

Is there a way to dynamically add multiple text fields for color and choose design based on user input? For instance, if the user enters 5 in the quantity field, how can I replicate the color and choose design fields 5 times? Additionally, how should I st ...

The error message "Required parameter not provided" appeared when trying to utilize a nested dynamic route in Next.js

Issue: The error message indicates that the required parameter (plantName) was not provided as a string in getStaticPaths for /plants/[plantName]/streaming-data/[panel] The error above is being displayed. My folder structure follows this pattern: plants & ...

Event delay with JavaScript and jQuery

In my WordPress (WooCommerce) website, I am working on creating a quantity field... It is functioning properly; however, I want to trigger an event when the + or - buttons next to Quantity are pressed in order to "Update cart". This is what I have tried: ...

Sending data using Ajax to the server-side code in ASP.NET

Struggling to successfully pass a series of values through Ajax to a code-behind method in order to insert the data into a database table. However, encountering issues where string variables are being received as empty strings and int variables as 0. The ...

Having issues with passing data to a Modal on eventClick using FullCalendar with ReactJS, receiving a "cannot read property of undefined" error. Any advice on how

My MERN stack application utilizes the FullCalendar plugin, even though I am aware that mixing jQuery with React is not ideal. Unfortunately, I am a novice developer and running behind schedule. The goal is to allow users to click on an event on the calen ...