首页 > 解决方案 > Importing script and calling a method on a variable

问题描述

I'm new to typescript and I'm trying to use a bit of code I found online to change links to look nice for my site,

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

I included that into my index.html, and it works great, until I load a component, I spent a lot of time looking around and found that I need to call $WowheadPower.refreshLinks();

To get the links to change when a new element is added, I wasn't sure how to declare that variable in typescript so I could tie it to various angular commands I wanted to do, unless I add it in a try catch:

loadScript(){
    try{
        // update tooltips

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

I get an error that says Cannot find name '$WowheadPower' but I saved it anyway, and somehow on my page it works as I want it too.

It works perfect, but I still got the error so I declared it

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

and it broke, I assume because I overwrote the correctly variable that has the right method.

Now I have to leave the error in to get functionality, but the error stops me from compiling when I ng serve. Until I hit save on VScode then it works fine again.

Any thoughts on how to resolve this?

标签: javascripttypescriptvisual-studio-codeangular8

解决方案


由于 $WowheadPower 是从另一个文件导入的外部变量,因此您可以告诉 typescript 它存在而不显式声明它:

declare var $WowheadPower: any

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


推荐阅读