MFL
MFL

Reputation: 69

Return type for static async method

Can someone advise the correct Typescript return type for the static async method loadArray() below?

Promise<boolean> as shown below produces the error: "The return type of an async function or method must be the global Promise type.ts(TS1064)"

Note that I have no trouble creating correct return types for non-static async methods.

I'm using TypeScript 3.2.2.

class DataItemUpdate {
  type: string;
  json: {
    id: string;
    owner: string;
  }
  static async loadArray(outputForAppend: DataItemUpdate[], inputKeys: string[], typeName: string): Promise<boolean> {
    const redisMulti = redisClient.multi();
    inputKeys.forEach(keyName => {
      redisMulti.get(`${keyName}:json`);
    })
    let loaded: (string | null)[] = await redisMulti.execAsync();
    if (loaded.includes(null)) { // If any item failed to load
      return false
    } else {
      outputForAppend.push(
        ...loaded.map(jsonString => {
          return { 'type': typeName, 'json': JSON.parse(jsonString) };
        })
      )
      return true
    }
  }
}

Upvotes: 0

Views: 3061

Answers (2)

MFL
MFL

Reputation: 69

Problem solved by removing

import Promise = require('bluebird');

from the top of the file. That was the problem - some issue relating to TypeScript and Bluebird promises.

Upvotes: 0

mickaelw
mickaelw

Reputation: 1513

There are two choices:

Number one

According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function the return of async function is implicitly wrapped to a Promse.

So you can add "lib": ["es2018", "dom"] into compilerOptions part of the tsconfig.json file.

Number two

The definition of your function is : static async loadArray(...): Promise<boolean> and the type return is Promise<boolean>

In your code you return false or true so there is a mismatch between both.

You can resolve it:

  • you change the type return of the function to boolean

or

  • you can do Promise.resolve([your_boolean]) or Promise.reject([your_boolean])

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Upvotes: 3

Related Questions