首页 > 解决方案 > 打字稿,如何引用未导出的 OAuth2Client?google-api-nodejs-客户端

问题描述

我正在尝试遵循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;
}

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

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

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

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

至于类型别名:

type OAuth2Client = typeof GoogleApis.prototype.auth.OAuth2.prototype;

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

标签: javascripttypescriptgoogle-api

解决方案


截至 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();

感谢angelxmoreno提供的示例


推荐阅读