0

I have a JavaScript file (TestAdd.js), containing a function that I'd like to use from within a TypeScript file (CalcTest.ts)

Here is the JavaScript:

var TestSum;     
(function (TestSum) {    
var Cal = (function () { 
    function Cal() { 
    } 
    Cal.prototype.doAdd = function (a, b) { 
        return a + b; 
    } 
}) 
})

And here is the TypeScript:

/// <reference path = "Calc.d.ts" />
var obj = new TestAdd.Cal(); 
console.log("Add: " +obj.doAdd(40, 25));

I've created an ambient declaration file (Calc.d.ts) to declare the external module:

declare module TestAdd{ 
    export class Cal { 
        doAdd(a:number, b:number) : number; 
    } 
} 

My understanding from following several tutorials is that this should allow me to instantiate the type and use the method from the external JS file. I'm expecting the result of 65 to be logged to the console, but I am instead getting ReferenceError: TestAdd is not defined.

Sean
  • 5
  • 3

1 Answers1

0

The reference path comment won't import the function for you. You need to import it. e.g. assuming test add as export as your default export:

/// <reference path = "Calc.d.ts" />
import testAdd from 'TestAdd.js'

var obj = new testAdd.Cal(); 
console.log("Add: " +obj.doAdd(40, 25));

and in your TestAdd.js

add export default TestSum at the bottom

Damian Green
  • 6,895
  • 2
  • 31
  • 43
  • TestAdd.js is not being recognized as a module. Does an export keyword need to be added to the JavaScript for the declaration file to pick it up? – Sean Oct 07 '19 at 13:56
  • Hi @Sean did you resolve the above? If you did would mind sharing your solution please? I'm seeing the exact same problem when I try any of the tutorials associated with TypeScript...`TestAdd is not defined` – bhreinb Feb 15 '23 at 11:09