arrays - 类型化类的 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
}
}
谢谢您的帮助!
解决方案
你可以在不扩展的情况下实现你想要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);
推荐阅读
- php - 当我使用 isset($_SESSION['name']) 并且无法在网站中获取值时?
- java - 调用 notifyAll 时出现 IllegalMonitorStateException
- google-apps-script - google app script] 如何使用电子表格地址创建非黑客代码
- python - Matplotlib ModuleNotFoundError
- jmeter - 在 JMeter 的插件管理器窗口中下载/升级插件时出错
- html - 与引导程序的响应对齐
- java - “Stream 类型中的方法 generate(Supplier ) 不适用于参数 (int)”,List = Stream.generate()
- android - 动态 EditText 未在线性布局中添加高于指定元素
- arrays - 在迭代Ruby中为数组的每个元素分配对象属性值
- flutter - 在颤动中使用按钮手势旋转文本或图像