typescript - 在 lib.d.ts 中定义的变量中扩展类型定义

标签 typescript

我有使用 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/

相关文章:

node.js - 获取 JSON

typescript - 我的 Stripe 签名 key 是什么,我在哪里可以找到它?

angular - 如何在 Angular 5+ 中使用未编译的 TypeScript 导入 repo(并排除 .spec.ts 文件)

typescript - 如何从构造函数中访问静态成员

javascript - Ionic 3 - 所有导入都是未使用的警告(即使它们正在使用中)

javascript - 为什么 TypeScript 不会为此 promise 链抛出编译错误?

generics - TypeScript 泛型类 : Cannot assign to Generic Type Variable

Typescript - 基于另一个属性的条件属性

typescript - 如何在 NestJS 中设置类似 Angular 的配置环境文件?

typescript - 为什么实现接口(interface)的类中的泛型成员函数不能采用类(而不是接口(interface))类型的参数?