简体   繁体   中英

What is correct way to write d.ts file for js function?

I know there are a lot of questions related to this problem. I searched again and read all questions twice. I get some results but not all I want. Please help me to find my mistake.

These are my js and d.ts files

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

And

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

I use from my component like this

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

My import statements are below:

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

Everything compiles fine and builds succesfully but when I check at localhost it gives the error:

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)

My directory is like this:

在此处输入图片说明

Your other.js file should be encapsulated in a class and should be made available in the exports to be used.

    //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;

Then in your component ts file you can use it by writing on top of the file at imports level directly:-

declare var other:any 

Or if you have mentioned your .d.ts files correctly like the class and its protype properties as its internal functions:-

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

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