首页 > 解决方案 > 使用模拟数据:Typescript 不可分配给类型

问题描述

我是 Angular 的新手,我相信我以错误的方式设置了我的模拟数据,这会导致以下错误:

Argument of type '{ "name": string; "refCode": string; "contentId": string; "enabled": boolean;  }[]; } | { ...; }' is not assignable to parameter of type 'Item'.

更新了其他错误消息:

Types of property ... are incompatible.
  Type '{ "name": string; "refCode": string; "contentId": string }[]' is not assignable to type 'Item[]'.
    Property ... is missing in type '{ "name": string; "refCode": string; "contentId": string;}' but required in type 'Item'.

这是我的 json 文件内容:

{
  "data": {
    "items": [
      {
        "obj1": "one",
        "obj2": "two",
        "obj3": three
      },
      {
        "obj1": "four",
        "obj2": "five",
        "obj3": siix
        "subCategories": [
          {
          }
        ]
      },
      {
        "name": "Menu Option 1",
        "refCode": "opt1",
        "contentId": "0",
        "subCategories": [
          {}
   
        ]
      },
      {
        "name": "Menu Option 2",
        "refCode": "opt2",
        "contentId": "0"
      },
      {
        "name": "Menu Option 3",
        "refCode": "opt3"
      }
    ]
  }
}

在我的服务类中,我像这样导入它:

import dataItems from './shared/my-items.json';

并像这样声明它:

public menuItems: any;

然后我在我的组件类中迭代这里的项目:

const optionData = 
this.itemService.getMenuItems().data.items;
const resource = {};
if (itemData && itemData.length > 0) {
  this.items = [];
  itemData.forEach(element => {
    this.itemService.applyItemName(
      element
    );
    this.items.push(element 
  });
  this.itemService.categories = this.itemss;
}

最后是applyItemName()方法,它为给定的项目添加项目及其子项:

public applyItemName(item: Item) {
if (item.subCategories && item.subCategories.length > 0) {
  item.subCategories.forEach(subCategory => {
    subCategory.parent = category;
    this.applyItemName(subCategory);
  });
}

}

Item对象的模型在这里:

export class Category {
  public subCategories: Items[];
  public contentId: string;


  constructor(subCategories: Item[], enabled: boolean, name: string) 
  {
      this.subCategories = subCategories;
      this.enabled = enabled;
      this.name = name;
    }
  }

正如我所说,我是新手,我不确定我错过了什么。非常感谢任何提示。

标签: angulartypescript

解决方案


我认为存在的问题childCategories应该是可选的,因为在您的对象中的某些孩子中它不存在。添加?at 声明将使其成为可选:

export class Category {
  public childCategories?: Category[];

或者你总是可以将 childCategories 初始化为一个空数组

  public childCategories: Category[] = [];

推荐阅读