Typescript如何检查函数是否已定义(plugin,window.plugin)

时间:2016-10-10 18:34:52

标签: typescript

我在Typescript中转换了一个现有的js文件来进行检查:

if (typeof sweetAlert == "function") {               
    swal(title, message, "error");
} else {
    alert(message);
}

但我得到Cannot find name 'sweetAlert'Cannot find name 'swal'

如何在Typescript中进行类似的检查,并调用swal函数可能在别处定义? 感谢

1 个答案:

答案 0 :(得分:0)

您需要让编译器知道此sweetAlert存在:

interface Window {
    sweetAlert: Function;
}

if (typeof sweetAlert == "function") {               
    sweetAlert(title, message, "error");
} else {
    alert(message);
}

修改

尝试使用declare

declare function sweetAlert(title: string, message: string, type: string);

if (typeof sweetAlert == "function") {               
    sweetAlert(title, message, "error");
} else {
    alert(message);
}