gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:20:01 26 4
gpt4 key购买 nike

我有两个这样的类。

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

最佳答案

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

interface IThing {
active: boolean
}

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

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

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

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

关于javascript - 如何在 TypeScript 中声明具有嵌套对象数组的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42621345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com