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

Navigating a text input field in a NextJS application

Having trouble with handling input from a textarea component in a NextJS app. This is the structure of the component: <textarea placeholder={pcHld} value={fldNm} onChange={onChangeVar} className="bg-cyan-300" ...

Tips for incorporating nested generics in Typescript

Currently, I am developing a straightforward activity execution framework that allows developers to define activities which can be executed within a workflow. To enhance type safety and boost developer productivity by utilizing type hints, I aim to incorp ...

What is the process of creating a typeorm relationship between orders and products?

My Orders Entity file in TypeOrm looks like this: @Entity('orders') export class OrdersEntity { @PrimaryGeneratedColumn('uuid') id: string; @CreateDateColumn() created: Date; @UpdateDateColumn() updated: Date; @Column('t ...

How can a property be made mandatory in Typescript when another property is set as optional?

Currently, I am unsure about what to search for in order to fulfill the following requirement. Specifically, I am utilizing the given type for react props: interface ComponentProps { message : string, minValue? : number, minValueValidationMessage? ...

Exploring the possibilities of TypeScript/angularJS in HTTP GET requests

I am a beginner in typescript and angular.js, and I am facing difficulties with an http get request. I rely on DefinitelyTyped for angular's type definitions. This is what my controller code looks like: module game.Controller { 'use strict& ...

What is the best way to activate an alert or swal function just once instead of repeatedly?

I am just starting to learn Angular. Currently, I have an application that contains two variables related to the status of financial transactions. These variables are: tab1TrxMessage, which holds any important messages, and tab1TrxStatus that indicates wh ...

Establish Vue and the Vue CLI

I'm currently in the process of setting up a new Vue project. I started off by installing @vue/cli using the following command: PS D:\OpenServer\domains\vue3-example> npm install -g "@vue/cli" Next, I attempted to create t ...

Prevent regex special characters in JavaScript while preserving the original string for keyword matching

As I develop my web page, I encountered an issue while trying to highlight text based on user input in the search box. My search algorithm matches each space-separated keyword, but ran into problems when including brackets in the search term. This caused a ...

Output in Typescript for the chosen option

A message can be sent based on the user's choice of either Now or Later. If the user selects Now, the message will be sent immediately. If Later is chosen, a date format option needs to be created for setting a future date. <label for=""& ...

Having trouble dispatching a TypeScript action in a class-based component

I recently switched to using this boilerplate for my react project with TypeScript. I'm facing difficulty in configuring the correct type of actions as it was easier when I was working with JavaScript. Now, being new to TypeScript, I am struggling to ...

Storing a portion of JSON data within a function called in the HTML document

I've been working with Angular and need to save a portion of JSON data in a variable within a function that is called in an HTML file: <select id="postazione" onchange="postazioneSelezionata()"> <option value="" selected disabled >Cho ...

The expected property 'label' is not found in the object type '{ handleClick: () => void; }', but it is required in the object type '{ handleClick: () => void; label: string; }'

I'm encountering difficulties when describing the types of my props. The issue arises with the following code: <PostButton handleClick={props.upvote}/> <PostButton2 handleClick={props.downvote}/> An error message is displayed: Pro ...

Adjusting the speed of Vuetify transitions: A guide on setting the perfect transition speed

Looking to have an audio player component smoothly slide up from the bottom of its parent component? You can nest it within a <v-slide-y-transition> Vuetify component, but how can you control the speed of the sliding animation? <v-parallax src= ...

Disable multiple buttons at once by clicking on them

What is the best way to disable all buttons in a menu when one of them is clicked? Here is my code: <div class="header-menu"> <button type="button"> <i class="fa fa-search" matTooltip="Filter"& ...

The Typescript compiler will continue to generate JavaScript code even if there are compilation errors

As a fresh learner of TypeScript, I have been experimenting with some basic concepts. Below is the code from my file app1.ts: class Monster { constructor(name, initialPosition) { this.name = name; this.initialPosition = initialPosition ...

Using Vue router with hash mode may present issues when deploying on Github Pages

Issue with accessing a specific page via URL Greetings everyone, I am facing a small problem with my project. I have a "boilerplate" project using Vue3 + Laravel. I wanted to create a link for people to navigate to a specific page. For example, here is th ...

`Incorporate existing HTML data into Vue view-model`

My goal is to utilize Vue with pre-rendered HTML initially. While we may not continue this approach in the future, for now it seems more convenient to keep the server code intact and use Vue to handle client-side logic. I have been unable to find resource ...

"Unexpected Type Inference Issue: A variable initially defined as a string inexplicably transforms into 'undefined'

Currently, I am incorporating the await-to-js library for handling errors (specifically utilizing the to method from the library). In an intriguing scenario, the variable type shifts to string | undefined within a for..of loop, whereas outside of the loop ...

Do not use a template for keying. Instead, place the key directly on physical elements

I'm trying to incorporate the image preview feature using the image component within the View Design framework, but I keep encountering an error. You can find the Component url here under Example 5. Below is the code snippet: <template> < ...

Tips for updating the data value of a specific block using Vue.js

I am looking to develop a basic Vue.js application. Within this app, I have multiple counter blocks that are rendered using the v-for directive. In my data object, I initialize a 'counter: 0' instance. My goal is to increment and decrement only o ...