简体   繁体   English

Typescript 类型化类数组

[英]Typescript Array of Typed Classes

I am new to to development overall, so please pardon my ignorance.I am trying to understand how to use Typescript classes to combine two arrays of a given class我是整体开发新手,所以请原谅我的无知。我试图了解如何使用 Typescript 类来组合给定 class 的两个 arrays

Using the following example the ValidationError class consists of a property and an error message.使用以下示例,ValidationError class 由属性和错误消息组成。 The MyErrors class is an array of the ValidationError class. MyErrors class 是 ValidationError class 的数组。 I have various modules that will return a MyErrors and want to then concatenate them into a single array of ValidationErrors我有各种模块将返回 MyErrors 并希望将它们连接到单个 ValidationErrors 数组中

Ultimately I would like it to look something like the following:最终我希望它看起来像下面这样:

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

Below is my starting place:下面是我的起点:

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
    }
}

Thank you for your help!谢谢您的帮助!

You could achieve what you want without extending Array at all.你可以在不扩展Array的情况下实现你想要的。
The spread syntax allows you to call Array.push() with elements from another array. 扩展语法允许您使用另一个数组中的元素调用Array.push()

const allErrors: ValidationError[] = [];

allErrors.push(new ValidationError("property", "error"));

const moduleA: ValidationError[] = [ /* ... */ ];
const moduleB: ValidationError[] = [ /* ... */ ];

// Here's the nice bit using the spread syntax
allErrors.push(...moduleA, ...moduleB);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM