php_nub_qq
php_nub_qq

Reputation: 16055

Type '{}' is not assignable to type 'number'

So I understand the idea behind async/await is just a prettier way to use promises but apparently I'm not understanding it correctly.

async function a(): Promise <number> {
  return 5;
}

This is fine, returns a promise that is resolved with result 5.

async function a(): Promise <number> {
  return await new Promise(resolve => {
    resolve(5);
  });
}

error TS2322: Type '{}' is not assignable to type 'number'.
Property 'includes' is missing in type '{}'.

From what I understand, await will wait for the promise to resolve and return the result, which in this case is 5 and should work as the above example?

Upvotes: 1

Views: 3501

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68665

By default the new Promise() is equivalent to new Promise<{}>.

You inner Promise returns not a number, but an object. You need to ensure to compiler that it is a Promise with the type number.

Replace await new Promise with await new Promise<number>

async function a(): Promise<number> {
  return await new Promise<number>(resolve => {
    resolve(5);
  });
}

And check your code also, I think you can work with your code without the middle Promise

async function a(): Promise<number> {
      return await 5;
}

Upvotes: 5

Related Questions