导入脚本并在变量上调用方法

Importing script and calling a method on a variable

我是打字稿的新手,我正在尝试使用我在网上找到的一些代码来更改链接,使我的网站看起来更漂亮,

<script src="https://wow.zamimg.com/widgets/power.js"></script>
<script>var wowhead_tooltips = {
    "colorlinks": true,
    "iconizelinks": true,
    "renamelinks": true
    };
</script>

我将它包含在我的 index.html 中,并且效果很好,直到我加载一个组件,我花了很多时间环顾四周,发现我需要调用 $WowheadPower.refreshLinks() ;

为了在添加新元素时更改链接,我不确定如何在打字稿中声明该变量,以便我可以将它绑定到我想执行的各种 angular 命令,除非我将其添加到 try catch 中:

loadScript(){
    try{
        // update tooltips

        if(typeof $WowheadPower == 'undefined'){
            $.getScript('//wow.zamimg.com/widgets/power.js');
        } else {
            $WowheadPower.refreshLinks();
            console.log($WowheadPower)
        }
    } finally {}
}

我收到一条错误消息 找不到名称“$WowheadPower” 但我还是保存了它,不知何故在我的页面上它也能按我想要的方式工作。

它运行完美,但我仍然遇到错误,所以我声明了它

try{
    // update tooltips
    var $WowheadPower
    if(typeof $WowheadPower == 'undefined'){
        $.getScript('//wow.zamimg.com/widgets/power.js');
    } else {
    $   WowheadPower.refreshLinks();
        console.log($WowheadPower)
    }
} finally {}

它坏了,我想是因为我覆盖了具有正确方法的正确变量。

现在我必须保留错误以获取功能,但错误阻止我在 ng 服务时进行编译。直到我在 VScode 上点击保存,然后它再次正常工作。

关于如何解决这个问题有什么想法吗?

由于 $WowheadPower 是从另一个文件导入的外部变量,您可以告诉打字稿它存在而无需显式声明它:

declare var $WowheadPower: any

在你的代码开头写这个,这样你就可以告诉 TS 这个变量存在。理想情况下,您将编写一个正确定义 $WowheadPower 类型而不是 any 类型的接口。