【问题标题】:Typescript: initialize empty array when using extends Array<T>打字稿:使用扩展数组<T>时初始化空数组
【发布时间】:2020-08-18 01:07:41
【问题描述】:

我正在尝试添加一个方法,该方法属于使用 Typescript (3.7.5) 扩展 device 数组的类。

export class devices extends Array<device> {
    constructor(items?:Array<device>) {
        super(...items);
    }

    getDeviceByUid(uid: number): device {
        return this.filter(elmt => elmt.uid == uid)[0];
    }
}

但我还需要能够声明和定义一个空数组,就像我对普通数组所做的那样:

unfilteredDeviceList: devices = []; //error : Property 'getDeviceByUid' is missing in type 'undefined[]' but required in type 'devices'.

所以我这样尝试: unfilteredDeviceList: devices = new devices();

我在做最新的时候没有编译时错误,但是在运行时:Error: Uncaught (in promise): TypeError: super is not iterable (cannot read property Symbol(Symbol.iterator))

如何声明和定义一个扩展的空数组,或者我应该在构造函数中改变什么?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    以这种方式更改构造函数实现应该可以工作:

    class devices extends Array<device> {
        constructor(items?:Array<device>) {
            super();
    
            if (items) {
                this.push(...items);
            }
        }
    
        getDeviceByUid(uid: number): device {
            return this.filter(elmt => elmt.uid == uid)[0];
        }
    }
    

    【讨论】:

    • 谢谢,它可以工作,但是现在我在 Angular 中使用它时得到TypeError: Found non-callable @@iterator。似乎Angular在进行一些刷新时将number传递给构造函数......我不明白为什么
    【解决方案2】:

    猜你现在由const arr: devices = new devices([])初始化

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 2017-11-16
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多