给定以下typescript函数:
public load(filter: IFilter): Promise<Material[]> {
return axios.get<Material[]>("data.json");
}
[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[]>'.
为了避免仅仅返回或铸造
AxiosPromise
从纸面上看,这是正确的。
return new Promise((resolve, reject) =>
axios.get<Material[]>("data.json")
.then((data) => resolve(data.data))
.catch((data) => reject(data.data)));
但这显然违反了法律
Promise constructor anti pattern
.