The TypeScript error occurs when attempting to assign a type of 'Promise<void | Object>' to a type of 'Promise<Object>' within a Promise.then() function

I'm currently working on a service to cache documents in base64 format. The idea is to first check sessionStorage for the document, and if it's not there, fetch it from IRequestService and then store it in sessionStorage. However, I've encountered a type error while trying to implement this.

The error message reads: Type 'Promise<void | GetDocumentResult>' is not assignable to type 'Promise<GetDocumentResult>'.

Here is the code snippet:

getDocument(requestId: string, documentId: DocumentID, requestService: IRequestService): Promise<GetDocumentResult> {
    if (this.storageKey in sessionStorage) {
      const documentsMap: Map<DocumentID, GetDocumentResult> = new Map(JSON.parse(sessionStorage.getItem(this.storageKey)!))
      if (documentsMap.get(documentId) !== undefined) {
        return new Promise(resolve => resolve(documentsMap.get(documentId)!))
      }
    }

    return requestService.getDocument(requestId, documentId)
      .then(value => {this.setDocument(documentId, value)})
}

I was anticipating the return type of Promise< GetDocumentResult >.then to be Promise< GetDocumentResult >, but it appears to be Promise<void | GetDocumentResult> instead. Can someone shed some light on why this is happening?

Thank you

Answer №1

It has been previously mentioned that the then callback returns void, not the result itself. If you are looking for the result, consider implementing the following:

getDocument(requestId: string, documentId: DocumentID, requestService: IRequestService): Promise<GetDocumentResult> {
  if (this.storageKey in sessionStorage) {
    const documentsMap: Map<DocumentID, GetDocumentResult> = new Map(JSON.parse(sessionStorage.getItem(this.storageKey)!));
    const document = documentsMap.get(documentId);
    if (document !== undefined) {
      return Promise.resolve(document);
    }
  }

  return requestService.getDocument(requestId, documentId).then(value => {
    this.setDocument(documentId, value);
    return value;
//  ^^^^^^^^^^^^
  });
}

Additionally, it is advisable to separate the cache lookup and storage logic (such as setDocument) into a distinct service. This service can maintain the documentsMap in memory instead of parsing JSON each time getDocument is invoked.

Answer №2

It appears that you may be facing an issue because you are not providing any return value within your .then() method.

Consider the following code snippet:

 .then(value => {this.setDocument(documentId, value)})

This results in your function returning a type of Promise<void> instead of Promise<GetDocumentResult>.

A corrected version would look like this:

getDocument(requestId: string, documentId: DocumentID, requestService: IRequestService): Promise<GetDocumentResult> {
    if (this.storageKey in sessionStorage) {
      const documentsMap: Map<DocumentID, GetDocumentResult> = new Map(JSON.parse(sessionStorage.getItem(this.storageKey)!))
      if (documentsMap.get(documentId) !== undefined) {
        return new Promise(resolve => resolve(documentsMap.get(documentId)!))
      }
    }

    return requestService.getDocument(requestId, documentId)
      .then(value => { return this.setDocument(documentId, value)})
}

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

Execute a series of Promises (or Deferreds) consecutively and have the flexibility to pause or stop at any point

Having an issue here. Need to make numerous consecutive http calls and the ability to stop the process at any point in time. The current solution I have involves jQuery and Deferreds, but it lacks proper interruption handling (still haven't transition ...

How do I preserve data within $scope upon switching views using ng-include?

Can you please take a look at this jsFiddle? http://jsfiddle.net/mystikacid/b7hqcdfk/4/ This is the template code: <div ng-app="myApp"> <div ng-controller="dataCtrl"> <div>Data : {{data}} (Value outside views)</div> < ...

Is it possible to nullify an object and utilize nullish coalescing for handling potentially undefined constants?

In my development work with React, I often utilize a props object structured like this: const props: { id: number, name?: string} = { id: 1 }; // 'name' property not defined const { id, name } = props; // the 'name' constant is now fore ...

Calculating the time gap between two consecutive "keyup" occurrences

I am in need of creating a basic point of sale system using Javascript. I have a barcode scanner that functions like a keyboard. My goal is to automatically identify when the input is coming from the barcode scanner and then generate a report with the sc ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

A comprehensive guide on creating translation files using grunt angular-translate from original JSON files containing translations

I have a unique angular application that requires support for multiple languages. To achieve this, I have implemented the angular translate task in the following manner. My goal is to create separate language files which can be loaded later using the useSt ...

Storing row details in Vue.js based on selected options from a dropdown menu

Displayed below is my code that generates a dynamic table. I am looking to save specific rows based on the selection made from a dropdown menu and then clicking on an update button. <b-field> <b-select name="contacted" id="" ...

A guide on seamlessly incorporating FlotJs functionalities into a ReactJs application

Having trouble integrating Flot charts into React due to a '$.plot' is not a function error. Here's the code I'm using: Script tags Index.html <script src="dist/libs/js/jquery.min.js"></script> <script src="dist/libs/js ...

Guide to easily printing a page in Angular 4 using TypeScript

When using my web app, there are certain pages where I need to print only a specific component without including the sidebar. I have written the following TypeScript code to achieve this: print() { window.print(); } The relevant HTML code begins with: & ...

Navigating the implementation of undefined returned data in useQuery hook within Apollo and ReactJS

I am facing an issue with my code where the cookieData is rendered as undefined on the initial render and query, causing the query to fail authentication. Is there a way to ensure that the query waits for the response from the cookie API before running? co ...

What is the process for invoking an External Javascript Firestore function within a Typescript file?

Trying to figure out how to integrate a Firestore trigger written in an external JavaScript file (notifyNewMessage.js) into my TypeScript file (index.ts) using Node.js for Cloud functions. Both files are located in the same directory: https://i.stack.imgu ...

Prevent the use of the + or - symbols within the body of a regular expression when

function validateNumberInput(){ userInput = document.getElementById('txtNumber').value; var numberPlusMinusRegex = /^[\+?\-?\d]+$/g; if (userInput.match(numberPlusMinusRegex)) { alert('Vali ...

What is the procedure for invoking a function when the edit icon is clicked in an Angular application

My current Angular version: Angular CLI: 9.0.0-rc.7 I am currently using ag-grid in my project and I encountered an issue when trying to edit a record. I have a function assigned to the edit icon, but it is giving me an error. Error message: Uncaught Re ...

Type parameter in express.js route

If I have this specific route in my Express.js server: router.get('/ad/:id', (req, res) => { const { id } = req.params Ad.getAd(id, (err, resp) => { if(err){ return handleError('Failed to load an ad' ...

Performing three consecutive Ajax requests in a Rails application

Recently, I developed a custom admin system for a local gym to manage payments, attendance, mailing, sales, and more. While everything is functioning smoothly, there seems to be an issue with the attendance feature. Occasionally, when taking attendance, an ...

Explore the properties within an array of objects through iteration

Here is the array I'm working with: const myArray = [{ id: 1, isSet: true }, { id: 2, isSet: false }, ...]; I only need to iterate over the isSet properties of the objects, ignoring all other properties. Initially, I attempted the following solution ...

Generating a two-dimensional array and setting its values in JavaScript

I need assistance with creating and initializing a two-dimensional array in JavaScript within an AngularJS application. My current approach is as follows: $scope.invalidVote = []; for (var i = 0; i < $scope.arry1.length; i += 1) { $scope.answersCou ...

Crushing jQuery's Sortable/Droppable

Having a little issue here. I want to be able to toggle the sortable plugin's behavior by clicking a button - basically switching between sort mode and view mode. I've attempted to achieve this with the following code: function enterSortMode(){ ...

Ways of invoking a component method from a service in Angular 2

I have a concept for creating a unique service that is capable of interacting with one specific component. In my application, all other components should have the ability to call upon this service and then have it interact with the designated component in ...

Rearrange HTML list items automatically according to changes in numeric sort order

I am working on a web page that features a dynamic ranked list. The items in the list are assigned a specific rank order number which changes based on user interactions elsewhere on the page. I have been exploring different options to automatically reorgan ...