36

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.

2
  • Possible duplicate of Calling JavaScript directly from TypeScript Commented Jul 12, 2016 at 1: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. Commented Jul 12, 2016 at 1:33

2 Answers 2

42

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

Sign up to request clarification or add additional context in comments.

Comments

17

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.

1 Comment

this is the answer I ended up actually using and it works.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.