Peter Kellner
Peter Kellner

Reputation: 15488

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;

Upvotes: 4

Views: 7876

Answers (2)

A Khudairy
A Khudairy

Reputation: 1492

Well it is expecting a promise, and you are returning a value. The selected answer makes sense. But there is also a very simple solution by using async if you are declaring a function like this

checkIfTrue(): Promise<boolean>{ return true; }

Then update this function as

async checkIfTrue(): Promise<boolean>{ return true; }

Upvotes: 0

Karol Majewski
Karol Majewski

Reputation: 25790

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

Upvotes: 11

Related Questions