How to declare an object with nested array of objects in TypeScript?

后端 未结 2 548
陌清茗
陌清茗 2021-01-14 09:52

I have two classes like so.

class Stuff {
  constructor() { }
  things: Thing[] = [];
  name: string;
}

class Thing {
  constructor() { }
  active: boolean;         


        
相关标签:
2条回答
  • 2021-01-14 10:16

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

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

    or

    blopp: Stuff[] = [
      {name: "aa", things: [<Thing>{active: true}  , <Thing>{active: false}]}, 
      {name: "bb", things: null}];
    }
    
    0 讨论(0)
  • 2021-01-14 10:23

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

    class Stuff {
        constructor(public name: string, public things: Thing[] = []) { }
    }
    
    class Thing {
        constructor(public active: boolean) {
    
        };
    }
    
    var blopp: Stuff[] = [
        new Stuff("aa", [new Thing(true), new Thing(false)]),
        new Stuff("bb", null)
    ];
    

    Or simply use interfaces:

    interface IThing {
        active: boolean
    }
    
    interface IStuff {
        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);
    
    */
    var Stuff = (function () {
        function Stuff(name, things) {
            if (things === void 0) { things = []; }
            this.name = name;
            this.things = things;
        }
        return Stuff;
    }());
    var Thing = (function () {
        function Thing(active) {
            this.active = active;
        }
        ;
        return Thing;
    }());
    var blopp = [
        { 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);

    0 讨论(0)
提交回复
热议问题