用于自定义元素的Typescript类装饰器

时间:2019-01-07 21:31:32

标签: typescript decorator

我试图了解类装饰器如何与Typescript一起工作。我编写了以下代码来创建@Component装饰器,以添加一些初始化自定义元素的方法:

export interface ComponentOptions {
    tag: string,
    style?: string,
    shadow?: boolean
}

export const Component = ( options: ComponentOptions ) => {

    // Check if the element tag name is a valid custom element selector
    validateSelector( options.tag );

    return ( target: any ) => {

        const element: any = class extends ( target as { new (): any } ) {

            constructor() {

                super();

                this._connected = false;
                this._canAttachShadowDom = ( options.shadow ) ? options.shadow : false;

                attachShadowDom( this );

            }

            connectedCallback() {

                if( super.connectedCallback ) {

                    super.connectedCallback();

                }

                this._connected = true;

            }

            disconnectedCallback() {

                if( super.disconnectedCallback ) {

                    super.disconnectedCallback();

                }

                this._connected = false;

            }

        };

        /**
        *   Check if custom element is already defined
        *   Create new custom element when element name is not defined;
        */
        if( !customElements.get( options.tag ) ) {

            customElements.define( options.tag, element );

        }

        return element;

    };

};

@Component({
    tag: 'counter-element',
    shadow: true
})
export class CounterElement extends HTMLElement {

    constructor() {
        super();
        console.log('initiliazing');
    }

}

问题1:构建装饰器后,我遇到了以下线程:Class Decorator in Typescript。在该线程中,开发人员展示了通过使用构造函数的原型向类添加功能的另一种方法。我的问题是:通过原型添加它或通过 类扩展。 (例如,我知道将CounterElement编译为var CounterElement = function()和CounterElement.prototype.title)。

问题2:有没有一种方法可以键入target,element并以另一种方式扩展,然后只需键入any?

0 个答案:

没有答案