[英]Typescript Array of Typed Classes
我是整體開發新手,所以請原諒我的無知。我試圖了解如何使用 Typescript 類來組合給定 class 的兩個 arrays
使用以下示例,ValidationError class 由屬性和錯誤消息組成。 MyErrors class 是 ValidationError class 的數組。 我有各種模塊將返回 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.