一位前同事编写了一小段 JavaScript(我什至不知道该怎么调用它。类?库?),我现在尝试在应用程序的 TypeScript 部分中使用它。我们遇到过一些类似的情况,我们只是向 d.ts 文件添加某种声明。我现在正在尝试这样做,但我对我想要使用的对象也是原始 JS 中的函数这一事实感到困惑。也就是说,它是通过 new 运算符创建的,但构造的对象具有方法。我希望有人能告诉我最好的方法。
这是原始的 JavaScript 类/库:
(function (geographies, $) {
geographies.map = function(elementId) {
var self = this;
// Other members elided
// Public Functions
self.findAddress = function (addressDesc, callback){
// elided
}
// Other public methods elided
// Private Methods
function _example() {
// elided
}
// Other private methods elided
}
}(window.geographies = window.geographies || {}, jQuery));
当然,这会导致在全局窗口命名空间中创建geographies
,并且geographies
有一个成员map
,它有方法,但是通过传入字符串参数的 new
创建的。这是在现有代码中使用 geographies.map
的示例(在此上下文中,self
仅指包含组件):
if ((self.editAddress.cityId() && self.editAddress.addressLine1())) {
if (map === null) {
map = new geographies.map("addressMapDiv");
}
self.mapVisible(true);
var query = (self.editAddress.addressLine1() ? self.editAddress.addressLine1() : "") +
(self.editAddress.cityDescription() ? " " + self.editAddress.cityDescription() : "") +
(self.editAddress.zipCode() ? " " + self.editAddress.zipCode() : "");
console.log(query);
map.findAddress(query);
}
现在我们开始在 TypeScript 中使用geographies
,因此希望通过某种方式来获取智能感知并对其进行类型检查,但没有计划重新实现它。我们只是希望 TypeScript 为我们提供一种方法来使用窗口命名空间中已存在的同一对象。我对此进行了一些尝试,但似乎都没有什么意义。我认为最大的问题是 geographies.map
需要可更新并接受字符串参数 elementId
,同时也成为具有自己方法的对象。这是我最近失败的尝试:
interface Map {
constructor(elementId: string): Map;
findAddress(addressDesc: any, callback: any): any;
// Other signatures elided
}
interface GeographiesStatic {
map: Map;
// Other members elided
}
declare var geographies: GeographiesStatic;
我应该使用声明类
吗?接口(interface)?我是否需要底部的 declare var
,还是会以某种方式杀死窗口命名空间中已有的同名对象?任何指导将不胜感激。
最佳答案
该代码使用揭示模块模式,通常在 TypeScript 中用 namespace
表示。该文件的一个简单声明是:
declare namespace geographies {
class map {
constructor(name: string);
findAddress(desc: any, cb: any): any;
}
}
关于javascript - 为现有 JavaScript 进行 TypeScript 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50955102/