TypeScript 可以在没有定义文件的情况下与 jQuery 交互吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12755570/
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-09-13 16:12:29  来源:igfitidea点击:

Can TypeScript interact with jQuery without a definition file?

typescript

提问by Ciel

I have been attempting to get to know this new 'TypeScript' stuff, and I am a bit curious on something.

我一直在尝试了解这个新的“TypeScript”东西,我对某些东西有点好奇。

Can it still work with existing javascript frameworks like jQuery withoutthe need for a definition file with all of those interfaces? I have been attempting to test this out manually, but so far am a little unsure of how far the functionality extends.

它是否仍然可以与现有的 javascript 框架(如 jQuery)一起使用,无需具有所有这些接口的定义文件?我一直在尝试手动测试这个,但到目前为止我有点不确定功能的扩展程度。

update

更新

by 'work' I am referring to simple functionality, not IDE features like auto-completion.

通过“工作”,我指的是简单的功能,而不是自动完成等 IDE 功能。

回答by Peter Olson

The simple answer is yes.

简单的答案是肯定的

TypeScript is able to interact fully with anyexisting Javascript library. You only need the definition file if you want tooling in the IDE to make it easier to use.

TypeScript 能够与任何现有的 Javascript 库完全交互。如果您希望在 IDE 中使用工具使其更易于使用,则只需要定义文件。

Also, if you don't include the definition file, the TypeScript compiler might get mad at you for using a variable that hasn't been defined in your code (like $). To get around that you might have to do something like

此外,如果您不包含定义文件,TypeScript 编译器可能会因为您使用了未在您的代码中定义的变量(如$)而生气。为了解决这个问题,你可能需要做一些类似的事情

declare var $;

That said, I'm not sure why you wouldn'twant to use the jQuery definition file. It surely makes it much more pleasant to write jQuery with.

这就是说,我不知道为什么你会不会想使用jQuery的定义文件。用它来编写 jQuery 肯定会变得更加愉快。

回答by Murat Sutunc

Yes you can. For example just write:

是的你可以。例如只写:

declare var $;

and you can basically use the JQuery framework without having to define anything else. This is also very handy when you are converting your existing libraries / porting code.

并且您基本上可以使用 JQuery 框架而无需定义任何其他内容。当您转换现有的库/移植代码时,这也非常方便。

回答by Valentin

Typescript allows you to declare variables in the descired scope using the declare variableor declare functionsyntax (see Section 1.1 on page 9 in the language specification). However, using ambient declarations can only be a short-term solution since you will effectively loose all of Typescript's static type checking and hence one of the most important advantages of Typescript over Javascript.

Typescript 允许您使用declare variableordeclare function语法在所需范围内声明变量(请参阅语言规范第 9 页的第 1.1 节)。但是,使用环境声明只能是一种短期解决方案,因为您将有效地失去 Typescript 的所有静态类型检查,因此是 Typescript 相对于 Javascript 的最重要优势之一。