Here is a TypeScript function example:
public load(filter: IFilter): Promise<Material[]> {
return axios.get<Material[]>("data.json");
}
When using TypeScript, an error may occur due to incompatible types:
[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[]>'.
To address this issue without using the Promise constructor anti-pattern, the following approach can be taken:
return new Promise((resolve, reject) =>
axios.get<Material[]>("data.json")
.then((data) => resolve(data.data))
.catch((data) => reject(data.data)));
It is important to avoid the Promise constructor anti-pattern as discussed here.