Skip to content Skip to sidebar Skip to footer

How To Declare An Object With Nested Array Of Objects In Typescript?

I have two classes like so. class Stuff { constructor() { } things: Thing[] = []; name: string; } class Thing { constructor() { } active: boolean; } I tried to declare

Solution 1:

You should be using the new keyword to instantiate your objects:

classStuff {
    constructor(public name: string, public things: Thing[] = []) { }
}

classThing {
    constructor(public active: boolean) {

    };
}

varblopp: Stuff[] = [
    newStuff("aa", [newThing(true), newThing(false)]),
    newStuff("bb", null)
];

Or simply use interfaces:

interfaceIThing {
    active:boolean
}

interfaceIStuff {
    name:string;things:IThing[]
}

var blopp:IStuff[]= [
    { name:"aa", things: [{ active:true }, { active:false }] },
    { name:"bb", things:null }];

It is important to determine if you need classes or interface as some things will not work with anonymous objects:

/*
class Stuff {
	constructor(public name: string, public things: Thing[] = []) { }
}
class Thing {
	constructor(public active: boolean) {

	};
}
var blopp: Stuff[] = [
	{ name: "aa", things: [{ active: true }, { active: false }] },
	new Stuff("bb", null)
];
console.log("Is blopp[0] Stuff:", blopp[0] instanceof Stuff);
console.log("Is blopp[1] Stuff:", blopp[1] instanceof Stuff);

*/varStuff = (function () {
    functionStuff(name, things) {
        if (things === void0) { things = []; }
        this.name = name;
        this.things = things;
    }
    returnStuff;
}());
varThing = (function () {
    functionThing(active) {
        this.active = active;
    }
    ;
    returnThing;
}());
var blopp = [
    { name: "aa", things: [{ active: true }, { active: false }] },
    newStuff("bb", null)
];
console.log("Is blopp[0] Stuff:", blopp[0] instanceofStuff);
console.log("Is blopp[1] Stuff:", blopp[1] instanceofStuff);

Solution 2:

try to use <> or the as keyword for casting:

blopp:Stuff[]= [
  {name:"aa", things: [{active:true} asThing , {active:false}asThing]}, 
  {name:"bb", things:null}];}

or

blopp:Stuff[]= [
  {name:"aa", things: [<Thing>{active:true}  , <Thing>{active:false}]}, 
  {name:"bb", things:null}];}

Post a Comment for "How To Declare An Object With Nested Array Of Objects In Typescript?"