使用 Typescript 中的 Javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21544893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:53:25  来源:igfitidea点击:

Using a Javascript Function from Typescript

javascripttypescript

提问by MrSteamfist

I am trying to build a nice windows phone application with an HTML front end. I want to use TYPESCRIPT to do my processing onto my html page. There is one javascript function which is crucial for my application to work - window.external.notify

我正在尝试使用 HTML 前端构建一个不错的 Windows 手机应用程序。我想使用 TYPESCRIPT 对我的 html 页面进行处理。有一个 javascript 函数对我的应用程序的工作至关重要 - window.external.notify

This method isn't created till runtime I assume, so I build a javascript wrapper function to determine if it exists when it is called.

这个方法直到我假设的运行时才会创建,所以我构建了一个 javascript 包装器函数来确定它在调用时是否存在。

if (window.external.notify != undefined)
    window.external.notify(msg);

The issue is I need to get my Typescript files to see this function. I am using Visual Studio 2012 and I have seen the post - How to use an exported function within the local moduleThe issue is when I just include my javascript file with the function I want to use I get the error TS2095.

问题是我需要让我的 Typescript 文件才能看到这个功能。我正在使用 Visual Studio 2012 并且我已经看到了帖子 -如何在本地模块中使用导出的函数问题是当我只包含我想要使用的函数的 javascript 文件时,我收到错误 TS2095。

error TS2095: Build: Could not find symbol

错误 TS2095:构建:找不到符号

Any ideas or help or possible SDKs to circumvent this issue?

任何想法或帮助或可能的 SDK 来规避此问题?

采纳答案by basarat

You need to tell typescript that this function exists on window.externalin order to use it. So :

您需要告诉打字稿此功能存在window.external才能使用它。所以 :

interface External{
    notify: Function;
}

if (window.external.notify != undefined)
    window.external.notify("your message");

回答by Jan Franz Palngipang

//notif.js

//notif.js

let notify = function(message) {
    alert(message);
}

//test.ts

//test.ts

declare function notify(message: string): any;
if(notify != undefined)
    notify("your message");

Make sure notif.js is loaded first.

确保首先加载 notif.js。