Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Figure Out How To Get TypeScript To Be Happy with Returned Promise

I have reduced my code to this simple example that just returns a promise function. The error TypeScript 3.2 gives me is:

Error:(1, 7) TS2739: Type '() => Promise<{}>' is missing the following properties from type 'Promise<{ hasErrored: boolean; }>': then, catch, [Symbol.toStringTag]

The associated code is

const fetchUserInfoPromise1: Promise<{ hasErrored: boolean }> = () => {
    return new Promise(function(resolve) {
        resolve({ id: 1, name: 'peter' });
    });
};
export default fetchUserInfoPromise1;
like image 435
Peter Kellner Avatar asked Dec 17 '22 18:12

Peter Kellner


1 Answers

Firstly, fetchUserInfoPromise1 is a function that returns a Promise, not a Promise itself.

const fetchUserInfoPromise1 = (): Promise<{ hasErrored: boolean }> => { /* ... */ }

Secondly, the type parameter used in your return type definition must match the one that is being resolved. The returned Promise is supposed to resolve with an object { hasErrored: boolean }, yet it resolves with { id: number, name: string }. You need to decide what you want to accomplish.

Example:

const fetchUserInfoPromise1 = (): Promise<{ id: number, name: string }> => {
  return new Promise(function (resolve) {
    resolve({ id: 1, name: 'peter' });
  });
};
like image 54
Karol Majewski Avatar answered May 25 '23 12:05

Karol Majewski