Currently, I am delving into learning TypeScript and encountering a hurdle while attempting to define a class in a TypeScript definition file and then utilize it in a TypeScript file.
The dilemma lies with a JavaScript "class" called "Facade," which serves as a well-known design pattern of the OpenLayers Library. The structure of this facade looks like this:
lib/carto-facade/OpenLayerFacade.js :
function OpenLayerFacade() {
this.map = new ol.Map({
layers: [
new ol.layer.Tile({source: new ol.source.OSM()})
],
view: new ol.View({
center: [43.5, 5.0],
zoom: 2
}),
target: 'map'
});
}
OpenLayerFacade.prototype.setViewCenter = function(latitude, longitude) {
this.map.getView().setCenter(ol.proj.fromLonLat([longitude, latitude]));
}
Subsequently, I wish to employ this facade in a TypeScript project. Consequently, I formulated my .d.ts file as follows:
lib/carto-facade/OpenLayerFacade.d.ts
declare interface OpenLayerfacade {
setViewCenter(latitude:number, longitude:number):void;
}
declare interface OpenLayerfacadeFactory {
new(divName:string): OpenLayerfacade;
}
export var OpenLayerfacade:OpenLayerfacadeFactory;
Now, I aim to utilize it in a TS script loaded by a browser:
/// <reference path="../typings/jquery/jquery.d.ts" />
/// <reference path="../lib/carto-facade/OpenLayerFacade.d.ts" />
import oli = require('../lib/carto-facade/OpenLayerFacade');
$(document).ready(function () {
var ol = new oli.OpenLayerFacade("map");
ol.setViewCenter(43.5, 6.0);
console.log("Map displayed");
});
While everything compiles (transpiles) successfully, upon loading my webpage containing the script, I encounter the following error:
Uncaught TypeError: Cannot read property 'OpenLayerFacade' of undefined
This issue arises when I attempt to instantiate a new "OpenLayerFacade".
I have been using require.js, therefore transpile with the option "module": "amd" in my tsconfig.json
The structure of my HTML File is as shown below:
<html lang="en">
...
What could be going wrong?
I believe that the solution to my predicament might lie within the TypeScript Handbook. Any guidance on locating the relevant information would be greatly appreciated.
Kind regards,