【问题标题】:Typescript Array of Typed Classes类型化类的 Typescript 数组
【发布时间】:2020-07-27 13:38:18
【问题描述】:

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

感谢您的帮助!

【问题讨论】:

    标签: arrays typescript class strong-typing


    【解决方案1】:

    您完全可以在不扩展 Array 的情况下实现您想要的。
    spread syntax 允许您使用另一个数组中的元素调用 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);
    

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 2012-10-03
      • 2017-10-11
      • 1970-01-01
      • 2012-11-04
      • 2018-02-05
      • 2022-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多