1
votes

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?

1
Type '{}' is not assignable to type 'number' seems like a far more appropriate title.jdgregson
Why are you using promise with async/await?Harsh Patel
@HarshPatel how else would you write this if you have a function that works with callbacks inside a()?php_nub_qq
I opened a bug on the type warning: github.com/Microsoft/TypeScript/issues/23114 .Blair Zajac

1 Answers

5
votes

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