【发布时间】:2021-01-15 00:07:38
【问题描述】:
我开始使用 TypeScript 并在插入到 api 的 React 应用程序中实现它。我有一个文件,我根据它们的实体集成所有现有端点,因此我可以稍后从我的组件中执行api.Todos.getAll()。
现在我不知道如何解决 TypeScript 输出给我的错误:
Type 'Promise<ResponseOrError<Todo[]>>' has no properties in common with type 'ResponseOrError<Todo[]>'. TS2559
这里的代码,错误是在我调用.get("/v1/todos")之前指向axiosClient:
import Axios, { AxiosResponse } from "axios"
import {ToDo} from "some/folder/my-model-file"
const axiosClient = axios.create({
baseURL: "https://some-dummy-api.com"
})
interface ResponseOrError<T> {
data?: T
error?: string
}
function responseHandler<T>(response: AxiosResponse, error: Error): ResponseOrError<T> {
if (error.message) {
return { error: error.message }
}
return { data: response.data }
}
const Todos = {
getAll: (): ResponseOrError<Todo[]> =>
axiosClient
.get("v1/todos")
.then((response: AxiosResponse, error: Error) => responseHandler<Todo[]>(response, error))
}
如果我这样做:
getAll: (): Promise<ResponseOrError<Todo[]>> =>
axiosClient
.get("v1/todos")
.then((response: AxiosResponse, error: Error) => responseHandler<Todo[]>(response, error)),
然后错误变为:
Argument of type '(response: AxiosResponse, error: Error) => ResponseOrError<Todo[]>' is not assignable to parameter of type '(value: AxiosResponse<any>) => ResponseOrError<Todo[]> | PromiseLike<ResponseOrError<Todo[]>>'. TS2345
我做错了什么?我该如何解决这个问题?
【问题讨论】:
标签: reactjs typescript promise axios