如何在TypeScript中声明具有嵌套对象数组的对象?

时间:2017-03-06 08:59:28

标签: javascript typescript

我有两个类似的。

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

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

我试图在我的应用程序中声明一个字段。

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

上述方法效果很好。但是,当我尝试提供一系列事物而不是null时,我得到的错误是它不能指定类型。

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

2 个答案:

答案 0 :(得分:3)

您应该使用new关键字来实例化对象:

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)
];

或者只是使用接口:

interface IThing {
    active: boolean
}

interface IStuff {
    name: string;
    things: IThing[]
}

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

确定是否需要类或接口很重要,因为有些东西不适用于匿名对象:

/*
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);

答案 1 :(得分:0)

尝试使用<>as关键字进行投射:

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

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