Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios, Typescript, and Promises

This may be more of a TypeScript question. I have a REST method that is called within my http library by Vue action. I'd like the resolve() method to return the typed array, but unless I do the conversion within the action.ts "then" method, I receive a '.length does not exist in type {}'

Is there any way to not have to re-cast 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
like image 904
Feech Avatar asked Sep 16 '17 22:09

Feech


People also ask

Does Axios use promises?

Axios is a modern, Promise-based HTTP client library. This means that Axios is used to send an HTTP request and handle their responses, all using JavaScript's promises.

Does Axios work with TypeScript?

Make sure to install axios before using the code snippets in this article. You can install axios by opening your terminal in your project's root directory and running the npm install axios command. Copied! Axios includes TypeScript definitions, so we don't have to install them separately.

How do you handle Axios promises?

Promises can be handled in two ways using modern JS - the async/await syntax, which was shown above, as well as . then() and . catch() methods.


1 Answers

You should declare the return type of the method.

e.g.:

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

What is being resolved does not get picked up as the expected generic type by the compiler, unfortunately.

like image 119
Shane Avatar answered Sep 20 '22 04:09

Shane