简体   繁体   中英

How to force a return type of Array onto typescript function

I'm using the Google Drive API to pull in comments related to a specific file. However, when I return the array of comments associated with a specific value, it seems Typescript thinks I'm returning void from the listCommentsForFile function, when in reality they will be in an Array

Because the googleComments variable is assumed to be void I can't run array methods on it like the forEach

Can someone point out how I can explicitly cast to Array , or let Typescript know that I'll be returning an Array ? I'm new to TypeScript so would love a nudge in the direction to learn how this works as well. Thanks

//Set my oAuth2Client and fileID vars
const googleComments = await listCommentsForFile(oAuth2Client, fileID.trim());
googleComments.forEach(async comments => {
  //Do stuff with the comment
});

/**
 * List the comments of all files
 * @param {GoogleApis.auth.OAuth2} auth an authorized OAuth2 client.
 * @param {string} fileId the id of the file we're pulling comments for
 */
async function listCommentsForFile(auth, fileId) {
  const drive = await google.drive({ version: "v3", auth });
  let commentsArray: any[];
  drive.comments.list(
    {
      fileId: fileId,
      fields: "*",
    },
    (err, res) => {
      if (err) return console.log("The Comments API returned an error: " + err);
      if (res && res.data.comments) {
        const comments = res.data.comments;
        if (comments.length) {
          comments.map((comment) => {
            commentsArray.push(comment);
          });
        } else {
          console.log("No comments found.");
        }
      }
      return commentsArray;
    }
  );
}

You can add a return type to your function. Since it is an anync function, the return type should be a promise of the type that you are returning.

async function listCommentsForFile(auth, fileId): Promise<any[]> {

But it would be better if you used an actual type for the comments instead of any .

Usually typescript can figure out return types on its own. The reason it can't in this case is that you forgot to return the comments!

Your return statements are inside the callback on drive.comments.list , which means that the callback is returning. The function itself doesn't actually return the value created by drive.comments.list .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM