34

I have a javascript file called ui.js.

Inside ui.js is UI setup code.

if (!("ontouchstart" in document.documentElement)) {
    document.documentElement.className += " no-touch";
    var jScrollOptions = {
        autoReinitialise: true,
        autoReinitialiseDelay: 100
    };

    $('.box-typical-body').jScrollPane(jScrollOptions);
    $('.side-menu').jScrollPane(jScrollOptions);
    $('.scrollable-block').jScrollPane(jScrollOptions);
}

I would like to be able to call this from typescript.

I don't want to convert the code to typescript as there are hundreds of lines and it's not really necessary. It just needs to be one once after the UI is ready.

It seems to me that I should be able to wrap it in a function, and then call that function from typescript.

But I have not been able to figure out how to do that.

Note: Not a duplicate of earlier question, as that was how to convert js, not use it directly with as little modification as possible.

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
Greg Gum
  • 33,478
  • 39
  • 162
  • 233
  • Possible duplicate of [Calling JavaScript directly from TypeScript](http://stackoverflow.com/questions/12710962/calling-javascript-directly-from-typescript) – choz Jul 12 '16 at 01:24
  • That answer has to do with `converting` js to typescript. In this case, I just want to use it as is, or with as little modifications as possible. – Greg Gum Jul 12 '16 at 01:33

2 Answers2

37

You have two main options.

Option 1: Add JS to your TS compilation context

Simply set allowJs to true in your tsconfig.json compilerOptions and then make sure the .js file is included using files/include/exclude etc.

Option 2: Declare your JS for use in your TS

e.g. if you are going to call a js function anExampleFunction you can simply create a declaration (in a .d.ts file):

declare const anExampleFunction: Function;

And now you will be able to call the function from TypeScript.

More

basarat
  • 261,912
  • 58
  • 460
  • 511
15

You can call JavaScript functions from external files with no worries. But you have to declare them so TypeScript knows about them. If you dont, your code will work, but you will get an error while compiling.

You can use an Anonymously-typed var:

declare var myFunction;

or an Interfaced-typed var:

interface __myFunction { } declare var myFunction: __myFunction;

You may also write this into a declaration file(but its not required). See also TypeScript documentation.

Mick
  • 8,203
  • 10
  • 44
  • 66