打字类的打字稿数组

问题描述 投票:0回答:1

我总体上不熟悉开发,所以请原谅我的无知。我试图了解如何使用Typescript类来组合给定类的两个数组

使用下面的示例,ValidationError类包含一个属性和一条错误消息。 MyErrors类是ValidationError类的数组。我有各种模块,这些模块将返回MyErrors并希望将它们连接到ValidationErrors的单个数组中]

最终,我希望它看起来像以下内容:

let allErrors = new MyErrors

allErrors.add("property_a","there was an error with property a") // add an error in the main module

let module_a = returns a MyErrors array
let module_b = returns a MyErrors array

allErrors.addAll(module_a) // Add all errors returned from module_a to allErrors 
allErrors.addAll(module_b) // Add all errors returned from module_b to allErrors 
//allErrors should now be an array of ValidationError items the include the items from the main module, module_a and module_b

下面是我的出发地:

export class ValidationError  {
    public property: string
    public error: string
    constructor(property: string, error: string){
        this.property = property;
        this.error = error;
    };  
}

export class MyErrors extends Array<ValidationError>{
    add(property: string,error: string) {
        let newError = new ValidationError(property,error);
        return this.push(newError);
    }
    addAll(errors: MyErrors) {
        return this.concat(errors); //MyErrors instance that concatenates to the declared instance
    }
}

谢谢您的帮助!

我总体上不熟悉开发,所以请原谅我的无知。我试图了解如何使用Typescript类来组合给定类的两个数组。使用下面的示例...

arrays typescript class strong-typing
1个回答
1
投票

您完全不需要扩展Array就可以实现所需的功能。spread syntax允许您使用另一个数组中的元素调用Array.push()

© www.soinside.com 2019 - 2024. All rights reserved.