gpt4 book ai didi

javascript - 在函数中使用动态导入时,如何在全局变量中指定类型信息?

转载 作者:行者123 更新时间:2023-12-02 22:06:15 25 4
gpt4 key购买 nike

我的简化服务器代码如下所示。

服务器.ts

import google from "googleapis";

const androidPublisher = google.androidpublisher("v3");

app.use('something', function(req, res, n){
...
})

...(only one of the dozens of other methods use androidPublisher)

我正在导入 googleapis 库以设置 androidpublisher 变量。然而,这个googleapis库很大,完全导入文件需要400ms~700ms,而导入其他库文件需要10ms~30ms。

因为我的环境是无服务器架构(firebase 函数),并且因为大约十分之一的请求实际上需要 androidPublisher,所以我想利用动态导入来导入 googleapis 当有必要时。否则,上述设置实际上会为每个启动新无服务器实例的请求增加 400 毫秒/700 毫秒的延迟,即使不需要 androidPublisher 也是如此。

所以我做了如下更改。

服务器.ts

let androidPublisherInstance:any;

async function getAndroidPublisher() {
const googleapis = await import("googleapis");

if (androidPublisherInstance === undefined) {
const ap = googleapis.google.androidpublisher("v3");
androidPublisherInstance = ap;
}
return androidPublisherInstance;
}


...(one of methods use getAndroidPublisher() to get androidPublisher instance)

通过上述设置,我仅在需要时使用全局变量和辅助函数来初始化 androidPublisher。这按预期工作,并且当第一次需要 androidPublisher 时会增加 400ms~700ms 的延迟。但是,我最终将 androidPublisherInstance 类型设置为 any。我无法正确定义类型,因为类型定义在 googleapis 内部可用,并且位于 getAndroidPublisher 函数内部。

因此,当我使用 androidPublisherInstance 时,我失去了使用 typescript 的所有好处,并且必须在使用方法/属性时玩猜测游戏。

而且我认为我必须使用全局变量,因为我不想在函数调用 getAndroidPublisher( )

我错过了什么吗?有没有一种方法可以使用动态导入并让客户端仅初始化一次而不需要使用全局变量?

最佳答案

您可以只导入类型。只要您仅在类型定义中使用它,而不是在值表达式中使用它,编译后的 JavaScript 将永远不会加载该模块:

import { androidpublisher_v3 } from "googleapis";
let androidpublisher: androidpublisher_v3 | undefined;

或者,为了确保您不会意外地在错误的位置引用它,请仅使用 import types :

let androidpublisher: import("googleapis").androidpublisher_v3 | undefined;

关于javascript - 在函数中使用动态导入时,如何在全局变量中指定类型信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59706951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com