如何在 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}];

原文由 Konrad Viltersten 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 653
2 个回答

您应该使用 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);

原文由 Emil S. Jørgensen 发布,翻译遵循 CC BY-SA 3.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}];
}

原文由 Vladu Ionut 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题