Property 'allSettled' does not exist on type 'PromiseConstructor'.ts(2339)

你说的曾经没有我的故事 提交于 2020-06-25 09:17:07

问题


I try to use Promise.allSettled API with TypeScript. Code here:

server.test.ts:

it('should partial success if QPS > 50', async () => {
  const requests: any[] = [];
  for (let i = 0; i < 51; i++) {
    requests.push(rp('http://localhost:3000/place'));
  }
  await Promise.allSettled(requests);
  // ...
});

But TSC throws an error:

Property 'allSettled' does not exist on type 'PromiseConstructor'.ts(2339)

I already added these values to lib option of tsconfig.json:

tsconfig.json:

{
  "compilerOptions": {
    /* Basic Options */
    "target": "ES2015" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "lib": [
      "ES2015",
      "ES2016",
      "ES2017",
      "ES2018",
      "ES2019",
      "ES2020",
      "ESNext"
    ] 
   // ...
}

TypeScript version: "typescript": "^3.7.3"

So, how can I solve this? I know I can use an alternative module, but I am curious about working with TypeScript natively.


回答1:


The types for Promise.allSettled() were only merged in January, and will apparently be released in TypeScript 3.8.

As an interim solution, you can declare a mock-ish type for the function yourself:

declare interface PromiseConstructor {
    allSettled(promises: Array<Promise<any>>): Promise<Array<{status: 'fulfilled' | 'rejected', value?: any, reason?: any}>>;
}



回答2:


It's ES2020 and at Stage 4, so not available everywhere without a polyfill. It got typed and merged into TS. Try installing the latest @types/node package and see if that pulls it in.

Update: Looks like it will be adding es2020.promise to the libs, when it does land.

Update: npm i typescript@3.8.0-beta woot woot!



来源:https://stackoverflow.com/questions/60276013/property-allsettled-does-not-exist-on-type-promiseconstructor-ts2339

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!