简体   繁体   English

从TypeScript调用JavaScript函数

[英]Calling JavaScript functions from TypeScript

What's the best way of importing and using JavaScript code within TypeScript? 在TypeScript中导入和使用JavaScript代码的最佳方法是什么?

I'm trying to use stuff like Bootstrap's modal.js within an Angular 2 Component written using TypeScript. 我正在尝试在使用TypeScript编写的Angular 2 Component中使用Bootstrap的modal.js之类的东西。

UPDATE: 更新:

The solution as suggested was to create a type declaration d.ts file for the js file to forward delcare things I needed to use, then the referenced js file implementation was used at runtime. 建议的解决方案是为js文件创建一个类型声明d.ts文件,以转发我需要使用的delcare,然后在运行时使用引用的js文件实现。

Shame there isn't a more automatic direct way but it gets the job done. 遗憾的是,没有更自动的直接方式,但它完成了工作。 For many common frameworks these d.ts type declarations are available as mentioned via http://definitelytyped.org/tsd . 对于许多常见框架,这些d.ts类型声明可通过http://definitelytyped.org/tsd提及。 I also didn't need to comment style reference the d.ts as it was already included in my compiled ts files. 我也不需要评论样式引用d.ts,因为它已经包含在我编译的ts文件中。

You can use type declaration or write your own. 您可以使用类型声明或编写自己的声明。 Take a look on this project http://definitelytyped.org/tsd/ 看看这个项目http://definitelytyped.org/tsd/

It has type definitions for many popular libraries. 它具有许多流行库的类型定义。 And also for angular-ui-bootstrap . 还有angular-ui-bootstrap

Then you can reference definition in Typescript like this: 然后你可以在Typescript中引用定义,如下所示:

///<reference path="../typings/angular-ui-bootstrap/angular-ui-bootstrap.d.ts"/>

In general you basically reference a library, then in typescript you should reference a type definition or provide your own declaration, like 一般来说,你基本上引用了一个库,然后在typescript中你应该引用一个类型定义或提供你自己的声明,比如

declare function hex_md5(value: string): string;

if you have javascript function hex_md5 defined somewhere above. 如果您在上面的某处定义了javascript函数hex_md5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM