typescript 在打字稿中声明对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47164971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:01:12  来源:igfitidea点击:

Declare Array of Object in typescript

typescript

提问by Nicolas S.

I am trying to declare:

我试图声明:

type ArticleModel = {
    _id: number;
    name: string;
}

Then in my class:

然后在我的课上:

public models: ArticleModel[];

Where models should be as you may have guess an array of ArticleModel.

模型应该在哪里,因为您可能已经猜到了一系列 ArticleModel。

But node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js throws:

但是 node_modules/webpack/node_modules/webpack-core/lib/NormalModuleMixin.js 抛出:

error TS2322: Type 'Object[]' is not assignable to type '{ _id: number; name: string; }[]'.
  Type 'Object' is not assignable to type '{ _id: number; name: string; }'.
    Property 'id' is missing in type 'Object'..

Any help would be appreciated.

任何帮助,将不胜感激。

Thanks in advance.

提前致谢。

回答by Nicolas S.

Ok my bad, I was re-declaring the variable later as:

好吧,我不好,我稍后重新声明变量为:

let models:Array<Object> = [];

Cheers

干杯

回答by Mike PG

if you want to instantiate your object array when you create your class, you can do this:

如果要在创建类时实例化对象数组,可以执行以下操作:

public models: ArticleModel[] = [];

This is in place of doing it in the class constructor.

这代替在类构造函数中执行此操作。