如何在TypeScript中使用嵌套对象数组声明一个对象? [英] How to declare an object with nested array of objects in TypeScript?

查看:53
本文介绍了如何在TypeScript中使用嵌套对象数组声明一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个这样的班级.

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

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

我试图像这样在我的应用程序中声明一个字段.

I tried to declare a field in my application like this.

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

以上方法效果很好.但是,当我尝试提供事物的数组而不是null时,我得到的错误是它不能以指定的类型分配.

The above approach works just fine. However, when I try to provide an array of things, instead of null, I get the error that it's not assignable the the type specified.

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

推荐答案

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

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

或仅使用接口:

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

这篇关于如何在TypeScript中使用嵌套对象数组声明一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆