A powerful trio: Axios, Typescript, and Promises

I am facing a TypeScript dilemma. I have a REST method that is being called within my http library by Vue action. I want the resolve() method to return the typed array, but if I do not convert it within the action.ts "then" method, I get a '.length does not exist in type {}' error.

Is there a way to avoid recasting the result to my typed array since it was already done in the http.ts method?

http.ts (partial)

getapps() {        
        return new Promise((resolve, reject) => {
            this.axios.post('/account/getapps').then((response) => {
                resolve(response.data as DomainAppType[]);
            }, (err) => {
                reject(err);
            });
         });
    }

action.ts

import { DomainAppType } from '../models/domainApps';

var actions = {
    LOGIN: function ({ commit }, params) {
        http.getapps(params.email, params.password).then(apps => {
            var appList = <DomainAppType[]>apps;
            console.log(appList.length);
        }).catch((err) => {
            console.log(JSON.stringify(err));
        })

      }
}
export default actions

Answer №1

It is important to include the return type of your method in order for it to be recognized by the compiler.

For example:

retrieveData(): Promise<DataType[]> {
    return new Promise((resolve, reject) => {...});
}

Unfortunately, the compiler may not recognize the expected generic type that is being resolved.

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

Adding an element in real-time to a sortable list item using VueJs

I'm working on a project with a sortable list and I have two main goals: To be able to add/remove LI elements from the list using a +/- symbol. The list includes a textarea with data - my challenge is storing this data properly when adding or removin ...

transmit information and documents to server using Axios

I am working on a project using ReactJs and I need to send data to a Laravel API using Axios. Here is the code snippet I have tried: export const send = (data, File) => { const formData = new FormData(); formData.append('media', File); ...

Tips for fixing type declaration in a generic interface

Here is a simple function that constructs a tree structure. interface CommonItem { id: string parent: string | null } interface CommonTreeItem { children: CommonTreeItem[] } export const generateTree = <Item extends CommonItem, TreeItem extends ...

The localhost on port 3000 seems to be malfunctioning on Windows when trying to develop a ReactJS app using Create React App

For the past few days, I have been encountering a few issues that I have been trying to resolve without success. I attempted to stop localhost:3000 with netstat -ano | findstr :3000 taskkill /PID myPIDhere /F Despite my efforts, I still see- TCP 0. ...

Using a memory cache in development with NextJS does not seem to be effective

When exporting my pages for my simple static blog site, everything runs smoothly and quickly. However, in development mode, the generation of posts is sluggish and I'm looking to implement caching to speed up the process. I have set up a file called p ...

Error TS2339: The 'selectpicker' property is not found on the 'JQuery<HTMLElement>' type

Recently, I integrated the amazing bootstrap-select Successfully imported bootstrap-select into my project with the following: <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstra ...

What is the best way to convert Arabic language HTML into a PDF document on the client side?

Utilizing jsPDF and vue js, I successfully implemented a feature to export PDFs. However, I encountered an issue with Arabic characters not displaying properly. Can anyone provide assistance in resolving this problem? ...

Guide to sending a HTTP POST request with parameters in typescript

I need assistance sending a POST request using parameters in the following format: http://127.0.0.1:9000/api?command={"command":"value","params":{"key":"value","key":"value","key":"value","key":value,}} I attempted to do this but encountered an issue: l ...

Utilizing Vue: Attaching click event to dynamically added elements

I am working on a Vue application that retrieves HTML content from an API. This HTML contains blocks with the class <div class="play-video">...</div> Using axios to call the API and a promise, I insert the content into the DOM like this: < ...

Developing a webpack configuration involving two distinct setups yet utilizing identical plugins

Currently, I am tackling a project based on vue.js where I need to develop two separate SPAs - one for the admin dashboard and another for the public side. My goal is to manage these projects separately but work on them simultaneously. It would be convenie ...

Issue with jsPDF: PNG file is either incomplete or corrupted

I'm encountering an issue while attempting to pass Image data to the addImage function. I have tried downgrading the versions of jspdf and html2canvas, as well as experimenting with different ways to import the two libraries, but the problem still per ...

"Dependency resolution failed," encountered an error while executing the command "npm install"

Currently, I am following the steps outlined in this guide to install the migration build of Vue 3. Upon reaching the stage where I am instructed to execute vue upgrade and confirm with y to install upgrades, an error is presented: npm ERR! code ERESOLVE ...

Introduce a specialized hierarchical data structure known as a nested Record type, which progressively ref

In my system, the permissions are defined as an array of strings: const stringVals = [ 'create:user', 'update:user', 'delete:user', 'create:document', 'update:document', 'delete:document&ap ...

Retrieving Data in Typescript Async Function: Ensuring Data is Returned Once All Code is Executed

I need help with waiting for data to be retrieved before returning it. The code below fetches data from indexedDB and sends it back to a component. I understand that observables or promises can accomplish this, but I am struggling with how to implement t ...

Missing from the TypeScript compilation are Angular5's polyfills.ts and main.ts files

Here is the structure of my Angular5 project. https://i.stack.imgur.com/tmbE7.png Within both tsconfig.app.json and package.json, there is a common section: "include": [ "/src/main.ts", "/src/polyfills.ts" ] Despite trying various solu ...

react state change not triggering re-render of paragraph

I recently started learning react and web development. To streamline my work, I've been using ChatGPT, but I'm facing an issue that I can't seem to solve. I'm trying to fetch movie descriptions from the TMDB API using movie IDs, but des ...

Having trouble displaying child nodes in MatTreeView with Angular 14?

In an Angular project, I am attempting to display a private group's data from GitLab (utilizing a public one for testing purposes). To achieve this, I have implemented the NestedTreeView component. While the parent nodes are displaying correctly, I am ...

IntelliJ IDEA does not support the recognition of HTML tags and directives

I seem to have lost the ability to switch between my HTML and TS files in Intellij IDEA; the tags, directives, and autocompletion in HTML are no longer working. Additionally, I'm receiving some warnings: https://i.stack.imgur.com/QjmNk.png Is there ...

Retrieving the location.host parameter within NgModule

I am currently working on integrating Angular Adal for authenticating my application's admin interface with Azure AD. However, I have encountered a challenge with the redirectUri setting. My goal is to dynamically retrieve the current app's host ...

Using Vuex Namespaces to Manage State in a Store

I've encountered a challenge in my project involving a complex Vuex store. This store is responsible for saving filter input values and transforming them into filters that can be used to query the backend later on. The issue arises when I need to appl ...