My challenge involves managing multiple typed Arrays containing different objects. I am searching for a way to create a function that can add a new blank object to any array, as long as the type has an empty constructor available.
Being new to Angular 2 and Typescript, I need this functionality for arrays that are part of a form. Having numerous arrays, I would greatly benefit from a generic solution that works universally.
someObject {
constructor() { this.someField = ""; ... }
someField: string;
...
}
someOtherObject {
constructor() { this.someOtherField = ""; ... }
someOtherField: string;
...
}
Array<someObject> someArray = someObject[{...}, {...} ...];
Array<someOtherObject> someOtherArray = someOtherObject[{...}, {...} ...];
// My desired function should be able to work with either of the above arrays
// Although 'new T()' is not valid in TypeScript
addRow<T>(array:Array<T>) : void {
array.push(new T());
}
I have knowledge of using instanceOf to identify an object's specific class. However, I'm yet to discover a method for accessing the type as an object within an Array.
The following code could potentially solve my issue, but it may fail when the array is empty. Despite this, it should still retain its typing to which theoretically enables creation.
if(array.length > 0 && array[0] instanceOf(someObject)) {
array.push(new someObject());
}
// else if instance of someOtherObject... and so forth
Is there a more effective way to achieve my goal, or perhaps a technique I am currently unaware of? Thank you.
EDIT: According to Alexander's suggestion, achieving dynamic behavior in Typescript is possible through:
addRow<T>(array:Array<T>, c: {new(): T}) : void {
array.push(new c());
}
addRow(someArray, someObject);
addRow(someOtherArray, someOtherObject);
However, usage in HTML poses limitations: e.g.
<div class="btn btn-default" (click)="addRow(someArray, someObject)"></div>
won't be functional due to the lack of understanding the someObject class definition in HTML context.