【发布时间】: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