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

2023-11-21

我有两节课都是这样的。

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

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

/*
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐