How to load an array of objects in typescript -
how convert simple javascript proper typescript syntax using class "add" method?
var i, rec; var myarray = []; (i = 0; < 10; i++) { rec = { name: "john", age: }; myarray.push(rec); }
i figured out how @ least define variable, can't use "add" method load it:
var myarray: { name: string; age: number }[] = [];
here pathetic attempt add method on class:
class myclass { name: string; age: number; add(inarg1: string, inarg2: number) { this.name = inarg1; this.age = inarg2; } } var myarray= new array<myclass>(); (i = 0; < 10; i++) { myarray.add("john", i); }
while above answer it's job, not reflecting requirements of having custom array specific classes. learning want share of experience in oop, since think solution providing more meaning.
you define class reflects requirements of object in array:
class myclass { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } }
you define custom array extends javascript array type.
class myarray<t> extends array<t> { add(element: t) { this.push(element); } }
the t
means define generic array can hold class provide when create it. furthermore extend javascript array type method add
.
let array = new myarray<myclass>(); array.add(new myclass('ford', 20));
as see in creation of new myarray
adding myclass
type argument. after can add objects type myclass
.
Comments
Post a Comment