【问题标题】:How to force a return type of Array onto typescript function如何将数组的返回类型强制到打字稿函数上
【发布时间】:2020-10-19 22:13:19
【问题描述】:

我正在使用 Google Drive API 来提取与特定文件相关的 cmets。但是,当我返回与特定值关联的 cmets 数组时,Typescript 似乎认为我正在从 listCommentsForFile 函数返回 void,而实际上它们将位于 Array

因为googleComments 变量被假定为void,所以我不能像forEach 那样在其上运行数组方法

有人可以指出我如何显式转换为Array,或者让Typescript 知道我将返回Array?我是 TypeScript 的新手,所以我很想知道它是如何工作的。谢谢

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

【问题讨论】:

标签: arrays typescript casting google-api


【解决方案1】:

您可以为函数添加返回类型。由于它是一个 anync 函数,因此返回类型应该是您要返回的类型的承诺。

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

但是,如果您对 cme​​ts 使用实际类型而不是 any,那会更好。

通常打字稿可以自己找出返回类型。在这种情况下它不能的原因是您忘记归还 cmets!

您的 return 语句在 drive.comments.list 的回调中,这意味着回调正在返回。函数本身实际上并不返回由drive.comments.list 创建的值。

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 2015-08-10
    • 2021-08-15
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 2017-04-13
    相关资源
    最近更新 更多