网站搜索

在 TypeScript 中声明对象数组


我正在尝试声明:

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

然后在我的课堂上:

public models: ArticleModel[];

正如你可能猜到的,models 应该是一个 ArticleModel 数组。

但是 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'..

任何帮助都将不胜感激。

提前谢谢你。

答案#1

好吧,我的错,我后来把变量重新声明为:

let models:Array<Object> = [];

干杯

答案#2

如果你想在创建类时实例化你的对象数组,你可以这样做:

public models: ArticleModel[] = [];

这是为了代替在类的构造函数中执行它。