3

Let's say I have a javascript file, myScript.js, with the following content:

function run(file) {
    // some operations
}

How can I use the 'run' function inside a TypeScript file?

I've read similar questions but didn't find their answers clear enough: where I declare the function? how do I reference the declaration file etc..

3
  • You need to write a declaration file for that script Commented Jul 4, 2016 at 10:05
  • 1
    Possible duplicate of Using a 3rd party js file with TypeScript Commented Jul 4, 2016 at 10:06
  • I think that the other answers are not details enough. Where should I declare it? where is the reference to the js file? That's the information I'm looking for Commented Jul 4, 2016 at 10:21

1 Answer 1

5

TypeScript does not know about the run function. You'll have to declare it:

declare function run(file: any): any;

Now this works:

run(myFile);

EDIT: you can also look into using "--allowJs" tsc parameter mentioned here, but I have no experience with it.

EDIT 2: If the external script is a published library, chances are that there is a typings file (.d.ts) for it. Check out the typings tool in that case.

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

5 Comments

Where should I declare it? where is the reference to the js file?
You put it in a .d.ts file (myfile.d.ts) and you reference it: /// <reference path="myfile.d.ts" />
@NitzanTomer thanks, now I can compile but I'm getting runtime error 'run is not defined'.
That probably means that you're not really including that actual js file and so run isn't defined
You can declare it in same file (using 'declare' keyword). But you have to provide the script at runtime (e.g using a script tag)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.