P
P
Phoen1xx2021-06-12 15:18:43
JavaScript
Phoen1xx, 2021-06-12 15:18:43

Why does reject return unknown?

Hello. Please tell me, I'm trying to wrap fetch with a function, for more convenient work with json:

interface ResponseData{
    status: boolean;
    data?: object;
}

function sendQuery(url: string, data: object): Promise<ResponseData>
{
  return fetch(url, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
  }).then((response: Response) => {
    return response.json();
  }).then((data) => {
      return new Promise((resolve, reject) => {
        resolve({
            status: true,
            data: data
        });
      });
  }).catch(() => {
      return new Promise((resolve, reject) => {
          reject({
            status: false
          });
      });
  });
}


An error:
Type 'Promise<unknown>' is not assignable to type 'Promise<ResponseData>'.

This error appears because of the catch block, for some reason ts thinks it will return Promise(unknown). I tried to change interface to type. Specifying the type of the catch function does not help.
PS Specifying a crutch in the form of Promise (any) does not seem to be the right solution.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kovalsky, 2021-06-12
@lazalu68

This happens because your function is not properly organized: you claim that sendQuery will return a promise, but in fact you return a promise (return fetch), which will return a promise in which ResponseData. If you want to return a promise, then you either 1) return the original one returned to you by fetch and the rest of the methods in the chain, or 2) return the one you created, like in the asynchronous delay example:

function delay(duration: number): Promise<any> {
    return new Promise(res => setTimeout(res, duration))
}

A
Aetae, 2021-06-13
@Aetae

Turned over too much.
Firstly: there are helpers Promise.reslove(data)and Promise.reject(error), and secondly: when returning from then\ catch, even they are not needed.

interface ResponseData {
  status: boolean;
  data?: object;
}

function sendQuery(url: string, data: object): Promise<ResponseData> {
  return fetch(url, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
  }).then(response => 
    response.json()
  ).then(data => ({
    status: true,
    data: data
  })).catch(() => {
    throw {
      status: false
    }
  });
}

Although your version is NOT wrong, just mindlessly overloaded, the problem is that TS, alas, cannot automatically infer the type of the construct , and therefore produces . Those. every time you use - you have to use it with generic: . new PromisePromise<unknown>new Promisenew Promise<Type>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question