0

Given the following typescript function:

public load(filter: IFilter): Promise<Material[]> {
    return axios.get<Material[]>("data.json");
}

Typescript returns the following error (types are not compatible)

[ts]
Type 'AxiosPromise<MaterialSpectrum[]>' is not assignable to type 'Promise<MaterialSpectrum[]>'.
  Types of property 'then' are incompatible.
    Type '<TResult1 = AxiosResponse<MaterialSpectrum[]>, TResult2 = never>(onfulfilled?: (value: AxiosResponse<MaterialSpectrum[]>) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<...>' is not assignable to type '<TResult1 = MaterialSpectrum[], TResult2 = never>(onfulfilled?: (value: MaterialSpectrum[]) => TResult1 | PromiseLike<TResult1>, onrejected?: (reason: any) => TResult2 | PromiseLike<TResult2>) => Promise<...>'.
      Types of parameters 'onfulfilled' and 'onfulfilled' are incompatible.
        Types of parameters 'value' and 'value' are incompatible.
          Type 'AxiosResponse<MaterialSpectrum[]>' is not assignable to type 'MaterialSpectrum[]'.
            Property 'length' is missing in type 'AxiosResponse<MaterialSpectrum[]>'.

In order to avoid just returning or casting the AxiosPromise I tried this:
On paper, it looks correct.

    return new Promise((resolve, reject) =>
        axios.get<Material[]>("data.json")
            .then((data) => resolve(data.data))
            .catch((data) => reject(data.data)));

But it clearly violates the Promise constructor anti pattern.

Jim
  • 14,952
  • 15
  • 80
  • 167
  • 1
    `return Promise.resolve(axios.get ......etc)` - and instead of resolve in the .then, just return data.data, and throw data.data in the catch - not sure what anti-pattern that may be though – Jaromanda X Oct 23 '18 at 08:02

1 Answers1

2

You can "wrap" the promise returned by axios.get in Promise.resolve, like so

the .then and .catch need to be rewritten too (I've simplified them a bit using new syntax for destructuring function arguments - probably used the wrong term there though)

return Promise.resolve(axios.get<Material[]>("data.json"))
.then(({data}) => data)
.catch(({data}) => { throw data; });
Jim
  • 14,952
  • 15
  • 80
  • 167
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87