12

I have a simple TypeScript (ts) which needs a function from a JavaScript file. How can I import that js file into ts file? Do I have to create a ts file for that js file to be able to use it in my ts file?

kind_robot
  • 2,383
  • 4
  • 31
  • 45

2 Answers2

24

The easiest way is to just declare the function you're using:

File1.js

function greet() { return "Hello!"; }

File2.ts

declare function greet(): string;

/* ... later ... */
var hi = greet();

If your scenario is more complex (i.e. multiple files referencing File1.js, or there are many functions in File1.js that would clutter up File2.ts), you can make a File1.d.ts file and reference that from File2.ts:

File1.d.ts

function greet(): string;

File2.ts

/// <reference path="File1.d.ts" />

/* ... later ... */
var hi = greet();
Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235
  • Hi Ryan, thank you this works! One file I use however has methods added to Math library. So Math.uuid.js file has three methods in it; Math.uuid() returns string, and other two... TS complains to this "declare function Math.uuid(): string;" (obviously). How would I bring these methods in? Thanks! – kind_robot Dec 06 '12 at 22:21
  • 2
    Found it! I declared this interface... interface Math { uuid(): string; } and it's all good. – kind_robot Dec 06 '12 at 22:31
  • 2
    Is there a way to automatically generate a *.d.ts file from the .js file? Thanks - dave – David Thielen Nov 20 '13 at 22:52
  • 1
    @DavidThielen some good explanations of why that's not easy to do here https://typescript.codeplex.com/discussions/451987. i'm sure there's much more written on the subject but this satisfied my questions – Simon_Weaver May 22 '14 at 19:36
2

Just for the archives,if you add a /// ref for a JavaScript file inside your TS file, the compiler will try to validate all the code in the JS files and throw a huge error list. Try it with jQuery or something like that and you'll see what I mean.

Joel Cochran
  • 7,139
  • 2
  • 30
  • 43
  • Yup, I have seen that. I put declare var $ and not include that ref in projects which don't have jquery the d.ts file. – kind_robot Dec 12 '12 at 15:19
  • That's the quickest way to add support for any type that you don't have a .d.ts file for. The nice thing about the definition files is you get Intellisense. – Joel Cochran Dec 20 '12 at 14:08
  • 1
    I use DefinitelyTyped files all the time, that's a great project. – Joel Cochran Dec 21 '12 at 11:15
  • it doesn't even let you do this (i'm not sure if this changed since 2012) - you get `Incorrect reference: Only files with a .ts extension are allowed` - or maybe you meant to rename the .js to .ts. either way you're certainly right that you get a big mess :-) – Simon_Weaver May 22 '14 at 19:37