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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With