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

上述方法效果很好。但是,当我尝试提供一组事物而不是 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/

相关文章:

angular - 如何将注入(inject)服务从父类(super class)继承到 Angular 2 中的子类组件

angular - Angular 2类型脚本定义错误

angularjs - $rootScope.$on 上的引用 'this' 为空

javascript - 为列表中的每个对象进行 api 调用

javascript - 第一次实现和使用 ace

javascript - 在 Javascript 中,typeof var !== undefined 等同于 if(var)

javascript - 尝试将用 typescript 编写的类导入 javascript NodeJs 显示错误

angular - Angular 10-无法使用HttpClient delete()强制错误

javascript - 不寻常的 Javascript 图像标题错误

javascript - 错误: .。不是 Backbone 中的构造函数