kind_robot
kind_robot

Reputation: 2523

Load js file into typescript file

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?

Upvotes: 12

Views: 16965

Answers (2)

Joel Cochran
Joel Cochran

Reputation: 7768

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.

Upvotes: 2

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221342

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();

Upvotes: 24

Related Questions