首页 > 解决方案 > 如何从同一个打字稿文件扩展一个类?

问题描述

我正在尝试继承同一文件中的类,但编译器会生成以下错误:

类 'FilterController' 在其声明之前使用。ts(2449) FilterData.ts(53, 7): 'FilterController' 在这里声明。

(属性)FilterController._typingValue:HTMLInputElement 只有基类的公共和受保护方法才能通过“超级”关键字访问。ts(2340)

export default class FilterData extends FilterController {
    private _dataValue: any;

    constructor(protected storageKey: string, protected typingValue: HTMLInputElement, protected containerMain: HTMLElement, protected listboxMain: HTMLElement, protected listboxSecondary: HTMLElement) {
        super(storageKey, typingValue, containerMain, listboxMain, listboxSecondary);
    }

    /*private set data(dataValue: any) { this._dataValue = dataValue; }
    private get data(): any { return this._dataValue; }*/

    public initComponent() :void {
        this.keypress();
    }

    private keypress() {
        super._typingValue.addEventListener('keyup', (_event: KeyboardEvent) => {
            //this.search(_event);
            alert("aee")
        });
    }


}

class FilterController {
    protected readonly _storageKey: string;
    protected readonly _typingValue: HTMLInputElement;
    protected readonly _containerMain: HTMLElement;
    protected readonly _listboxMain: HTMLElement;
    protected readonly _listboxSecondary: HTMLElement;

    constructor(protected storageKey: string, protected typingValue: HTMLInputElement, protected containerMain: HTMLElement, protected listboxMain: HTMLElement, protected listboxSecondary: HTMLElement){
        this._storageKey = storageKey;
        this._typingValue = typingValue;
        this._containerMain = containerMain;
        this._listboxMain = listboxMain;
        this._listboxSecondary = listboxSecondary;
    }
}

标签: typescript

解决方案


错误消息表明您正在使用一个尚未声明的类。在你的情况下,你FilterController在类的声明之前进行扩展。

解决您的问题的最简单方法是更改​​两个类的顺序。首先声明FilterController,然后FilterData扩展第一个类。


推荐阅读