2017-05-25 30 views
0

我知道有很多与这个问题有关的问题。我再次搜索并阅读所有问题两次。我得到了一些结果,但不是我想要的。请帮我找到我的错误。为js函数编写d.ts文件的正确方法是什么?

这是我的js和d.ts文件

//other.js file 
function myFunction() { 
console.log("Hello from d.ts file"); 
} 

而且

//other.d.ts file 
export module other { 
    function myFunction(): void; 
} 

我从我的组件使用这样

ngOnInit() { 
    console.log((other as any).myFunction()); 
} 

我的import语句都低于:

import * as other from '../js/other' 

一切编译罚款,并成功地建立,但是当我检查本地主机它给人的错误:

ERROR Error: Uncaught (in promise): TypeError: WEBPACK_IMPORTED_MODULE_3__js_other.myFunction is not a function TypeError: WEBPACK_IMPORTED_MODULE_3__js_other.myFunction is not a function at MineComponent.webpackJsonp.156.MineComponent.ngOnInit (mine.component.ts:39)

我的目录是这样的:

enter image description here

+0

难道你不能为你的js编写typescript版本,这样当你将它转换成.d.ts时,你会得到更好和更准确的类型定义。 –

+1

问题是您的js文件没有任何其他名称,并且浏览器只理解js不是ts文件,这就是为什么它会在您的IDE中引发错误的原因。 –

+0

@GauravPandvia不,我只能使用js文件。因为我没有时间为所有js文件写ts版本:/你知道我该如何修复它在js文件中? – vusala

回答

0

你other.js文件应封装并且应该在出口中提供以供使用。

//other.js file 
var other = (function(){ 

    function other(){ 
    //init class properties... 
    } 
    other.prototype.myFunction = function() { 
    console.log("Hello from d.ts file"); 
    } 
    /** 
    * add to global namespace 
    */ 


})(); 
exports.other = other; 
在组件TS

然后文件,您可以通过在文件的顶部,在进口水平直接写入使用它: -

declare var other:any 

或者,如果你已经提到你的.d.ts文件正确像该类和其原型属性作为其内部功能: -

//other.d.ts 
export declare class other{ 
    myFunction(): void; 
} 
+0

现在我可以从js文件中找到声明myFunction到d.ts文件。但是在组件中我无法访问,它无法找到声明 – vusala

+0

尝试在您的组件 –

+0

中声明“var other:any”,但它无济于事。但无论如何感谢您的回复。 – vusala

相关问题