简体   繁体   English

TypeScript 环境声明不起作用

[英]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)我有一个 JavaScript 文件 (TestAdd.js),其中包含一个 function,我想在 TypeScript 文件 (CalcTestts.

Here is the JavaScript:这是 JavaScript:

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

And here is the TypeScript:这是 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:我创建了一个环境声明文件 (Calc.d.ts) 来声明外部模块:

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.从以下几个教程中我的理解是,这应该允许我实例化类型并使用外部 JS 文件中的方法。 I'm expecting the result of 65 to be logged to the console, but I am instead getting ReferenceError: TestAdd is not defined.我希望将 65 的结果记录到控制台,但我却得到 ReferenceError: TestAdd is not defined。

The reference path comment won't import the function for you.参考路径注释不会为您导入 function。 You need to import it.你需要导入它。 eg assuming test add as export as your default export:例如,假设 test add as 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在你的TestAdd.js

add export default TestSum at the bottom在底部添加export default TestSum

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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