简体   繁体   中英

TypeScript ambient declaration not working

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.

The reference path comment won't import the function for you. You need to import it. eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM