0

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

Using the following example the ValidationError class consists of a property and an error message. The MyErrors class is an array of the ValidationError class. I have various modules that will return a MyErrors and want to then concatenate them into a single array of 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!

1 Answer 1

1

You could achieve what you want without extending Array at all.
The spread syntax allows you to call Array.push() with elements from another array.

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.