打字稿,如何引用未导出的 OAuth2Client?google-api-nodejs-client

Yor*_*evi 1 javascript google-api typescript

我正在尝试遵循https://developers.google.com/sheets/api/quickstart/nodejs教程我正在使用打字稿,我喜欢它提供的类型注释和自动编译功能,我想重新编写示例在打字稿和异步而不是回调中。可悲的是,我被卡住了,OAuth2Client。在我的代码中,我在这样的函数中创建了一个 oauth 客户端:

async function setupClient() {
  const content: string = await fs.readFile("credentials.json", "utf8");
  const credentials = JSON.parse(content);
  // eslint-disable-next-line camelcase
  const { client_secret, client_id, redirect_uris } = credentials.installed;
  const oAuth2Client: o2 = new google.auth.OAuth2(
    client_id,
    client_secret,
    redirect_uris[0]
  );
  type OAuth2Client = typeof oAuth2Client;
  return oAuth2Client;
}
Run Code Online (Sandbox Code Playgroud)

我想将该客户端委托给另外两个设置功能:

function setupAuthUrl(oAuth2Client, scopes) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: "offline",
    scope: scopes,
  });
  return authUrl;
}
function setupToken(oAuth2Client, code) {
  //code
}
Run Code Online (Sandbox Code Playgroud)

但是我正在努力注释 oauth2client 类型,因为它没有被任何东西直接暴露?有人会猜测它是在 'oauth2_v2' 命名空间下公开的吗?但似乎不是这样。

我一直在寻找一种在实例化之前引用这种类型的方法,最好是通过导入,遗憾的是,当通过npm install googleapis它安装这个库时,它不提供对这些google-auth-librarygoogleapis-common中的任何一个的依赖并公开以供进口。eslint 错误,除非它添加了依赖项,我很难理解为什么需要它,因为该类型应该可以轻松访问以完成代码。

至于类型别名:

type OAuth2Client = typeof GoogleApis.prototype.auth.OAuth2.prototype;
Run Code Online (Sandbox Code Playgroud)

这是我能找出的唯一选项,它不会为别名引发错误/警告(对象作为命名空间)。这既是一条很长的线,又是非常奇怪的一条线,也来自其他面向对象的语言

  • TLDR:在打字稿中访问 OAuth2Client 和其他类型的代码完成的首选方式是什么?

Yor*_*evi 5

截至 6 月 19 日,添加此功能的合并请求已获批准。 https://github.com/googleapis/google-api-nodejs-client/issues/2208

import { google, Auth } from 'googleapis';
const oauthClient: Auth.OAuth2Client = new google.auth.OAuth2();
Run Code Online (Sandbox Code Playgroud)

感谢angelxmoreno的例子