My goal is to incorporate an already existing library into my TypeScript project. The library contains a singleton object that I want to declare and utilize.
For example, within the xyz.js file, the following object is defined:
var mxUtils = {
/* some complex code */
findNode: function(node, attr, value)
{
// more complex code here
return node;
}
};
There exists only one global instance of mxUtils during runtime as it is an external library. I prefer not to rewrite or reimplement the entire library in TypeScript.
I attempted to declare this singleton object but encountered difficulties.
This is the code snippet I tried to use to declare the Object globally:
In Utils.d.ts:
declare interface ImxUtils {
findNode(node:any, attr:string, value:string):any;
}
declare var mxUtils: ImxUtils;
Although my compiler accepted this declaration, mxUtils is undefined during runtime.
In main.ts:
// performing some operations
export class fancyComponent implements OnInit {
// adding some magic...
var tmpNode = mxUtils.findNode(aNode, aString1, aString2);
}
Despite seeing a global mxUtils Object in my debugger, I am unable to access it within my fancyComponent export.
If anyone can provide assistance with this issue, it would be greatly appreciated.
Also, note that xyz.js has been referenced and is present.
Take for example:
xyz.js:
function mxEventObject(name)
{
//
}
mxEventObject.prototype.getName = function()
{
return this.name;
};
In Utils.d.ts:
declare class mxEventObject {
constructor(name: string);
getName: () => string;
}
In main.ts:
export class fancyComponent implements OnInit {
// including some more magic...
var tmpEvent = new mxEventObject(aSampleString);
}
The above setup should work as intended.
Given the presence of a global object named mxUtils but my inability to access it within my fancyComponent export, I suspect there may be a scope issue at play here.