【问题标题】:How to solve "Type Promise<T> has no properties in common with type T" error?如何解决“Type Promise<T> has no properties in common with type T”错误?
【发布时间】: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


    【解决方案1】:

    你向 Promise.then 传递了错误的函数。

    onFullfilled 函数应该只接受一个参数 - 值。

    【讨论】:

    • axios documentation看来,如果没有.catch,则错误可用作.then的第二个参数。 (文档部分的最后一句)。
    • 您发布的文档说您可以传递两个回调,而不是一个带有两个参数的回调。 (Promise.then 可以接受两个回调:onfulfilledonrejected
    • 该死,看来我在这里是个菜鸟。感谢您指出这一点,它现在就像一个魅力。
    猜你喜欢
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    相关资源
    最近更新 更多