首页 > 解决方案 > 类型化类的 Typescript 数组

问题描述

我是整体开发新手,所以请原谅我的无知。我正在尝试了解如何使用 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
    }
}

谢谢您的帮助!

标签: arraystypescriptclassstrong-typing

解决方案


你可以在不扩展的情况下实现你想要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);

推荐阅读