How to solve "Type Promise<T> has no properties in common with type T" error?

Viewed 1611

I'm getting started with TypeScript and implementing it in a React app plugged to an api. I have a file where I integrate all existing endpoints depending of their entity, so I can do api.Todos.getAll() later from my components.

Right now I can't get how to solve the error TypeScript is outputting to me:

Type 'Promise<ResponseOrError<Todo[]>>' has no properties in common with type 'ResponseOrError<Todo[]>'.  TS2559

Here the code, the error is pointing as the axiosClient just before I call .get("/v1/todos"):

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))
}

If I do:

getAll: (): Promise<ResponseOrError<Todo[]>> =>
    axiosClient
      .get("v1/todos")
      .then((response: AxiosResponse, error: Error) => responseHandler<Todo[]>(response, error)),

Then the errors changes to:

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

What am I doing wrong ? How can I solve this?

1 Answers

You passed a wrong function to Promise.then.

The onFullfilled function should take only one argument - the value.

Related