我有使用 mootools 进行转换的遗留代码。 Mootools 引入了一个带有两个参数的新构造函数“Element”。我没有找到 mootools 的任何类型定义文件,所以我必须自己编写。
typescript 标准库(lib.d.ts)对 Element 的定义如下:
var Element: { prototype: Element; new(): Element; };
这使得扩展现有接口(interface)变得不可能。
我显然在尝试的是
interface Element {
new(s: string, s2: any): Element;
}
但是,编译器仍然提示
var c = new Element('p',{});
作为构造函数预期有 0 个参数,但得到了 2 个
。这里首选的解决方法是什么?
mootools 构造函数
var Element = this.Element = function(tag, props){
var konstructor = Element.Constructors[tag];
if (konstructor) return konstructor(props);
if (typeof tag != 'string') return document.id(tag).set(props);
if (!props) props = {};
if (!(/^[\w-]+$/).test(tag)){
var parsed = Slick.parse(tag).expressions[0][0];
tag = (parsed.tag == '*') ? 'div' : parsed.tag;
if (parsed.id && props.id == null) props.id = parsed.id;
var attributes = parsed.attributes;
if (attributes) for (var attr, i = 0, l = attributes.length; i < l; i++){
attr = attributes[i];
if (props[attr.key] != null) continue;
if (attr.value != null && attr.operator == '=') props[attr.key] = attr.value;
else if (!attr.value && !attr.operator) props[attr.key] = true;
}
if (parsed.classList && props['class'] == null) props['class'] = parsed.classList.join(' ');
}
return document.newElement(tag, props);
};
// Browser
var Browser = this.Browser = parse(navigator.userAgent, navigator.platform);
if (Browser.Element){
Element.prototype = Browser.Element.prototype;
// IE8 and IE9 require the wrapping.
Element.prototype._fireEvent = (function(fireEvent){
return function(type, event){
return fireEvent.call(this, type, event);
};
})(Element.prototype.fireEvent);
}
最佳答案
您不需要扩展Element
接口(interface),您需要的是扩展Element
变量的类型。这有点令人困惑,从 TS 的角度来看,这是两个独立的实体。方法如下:
declare const Element: { // If you do that in a .d.ts file, you don't need declare.
prototype: Element; // Element here is interface, we leave it unchanged.
new(): Element; // Standard constructor.
new(s: string, n: number): Element; // Your custom constructor.
};
const e = new Element('1', 2);
e.nodeName; // => string, i.e. result object implements Element interface.
关于typescript - 在 lib.d.ts 中定义的变量中扩展类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48788489/