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

Javascript 如何在TypeScript中声明具有嵌套对象数组的对象?,javascript,typescript,Javascript,Typescript,我有两个这样的班 class Stuff { constructor() { } things: Thing[] = []; name: string; } class Thing { constructor() { } active: boolean; } 我试图在我的应用程序中声明这样一个字段 blopp: Stuff[] = [ {name: "aa", things: null}, {name: "bb", things: null}]; 上述方法效果

我有两个这样的班

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 IThing {
    active: boolean
}

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

var blopp: IStuff[] = [
    { name: "aa", things: [{ active: true }, { active: false }] },
    { name: "bb", things: null }];
确定是否需要类或接口是很重要的,因为有些东西无法处理匿名对象:

/*
课堂材料{
构造函数(public name:string,public things:Thing[]=[]){}
}
阶级事务{
构造函数(public-active:boolean){
};
}
var blopp:Stuff[]=[
{name:“aa”,things:[{active:true},{active:false}]},
新材料(“bb”,空)
];
log(“Is blopp[0]Stuff:,blopp[0]Stuff实例”);
log(“Is blopp[1]Stuff:,blopp[1]Stuff实例”);
*/
var Stuff=(函数(){
函数内容(名称、内容){
如果(things==void 0){things=[];}
this.name=名称;
这个东西=东西;
}
归还物品;
}());
var Thing=(函数(){
功能对象(活动){
这个.active=active;
}
;
归还物;
}());
var blopp=[
{name:“aa”,things:[{active:true},{active:false}]},
新材料(“bb”,空)
];
log(“Is blopp[0]Stuff:,blopp[0]Stuff实例”);
log(“Is blopp[1]Stuff:,blopp[1]Stuff实例”)尝试使用
作为铸造关键字:

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

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

在我看来确实不错:@deceze不知道该告诉你什么。我收到一条错误消息。然而,根据被接受的答案的建议,我们成功了。也许我的IDE更唠叨(或者你的不够唠叨)。对TS不够精通,无法做出判断。用JavaScript谈论界面感觉非常奇怪。我仍然习惯于上课的概念。(我在C#中做OO已经超过15年了,但在JS中它似乎很奇怪……)你认为类在一般情况下更合适或更广泛地使用吗?我无法判断…Typescript最适合类,因为这是它的预期用途。如果您需要将一些JavaScript耦合到您的类型脚本,那么接口是很好的。如果thing数组(things:thing[])通过循环创建insdie stuff构造函数,那么接口是好的吗???@ksh应该是。在没有看到代码示例的情况下,回答这个问题有点困难。如果您愿意,您可以这样做?您认为您的建议与上面Emil在另一个答复中提出的基于构造函数的建议相比如何?我需要更多反馈以做出明智的决定。:)
blopp: Stuff[] = [
  {name: "aa", things: [<Thing>{active: true}  , <Thing>{active: false}]}, 
  {name: "bb", things: null}];
}