TypeScript: defining a top-level function

I use Lift as a web framework. Lift allows to generate JavaScript code and than to execute it on the page. I needed to execute a JavaScript function from that generated code. Since I use TypeScript for frontend development, I faced a problem here: How to create a global scoped function? Something like:


window.myFunction = function(){
// ...
}

 

Fortunately, I found a trick. Behold:


;( <any> window).myFunction = function():void {
// ...
}

 

For TSX:


;( window as any).myFunction = function():void {
// ...
}

 

Now you can call this function from JavaScript inside <script> tags on the page. But to call this function from a module, generated by Typescript, you need to declare it:


declare function myFunction():void

 

Now you can call this function from everywhere.

 

 

 

 

 

About Alexandre Kremlianski

Scala / Scala.js / JavaScript programmer

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.