【问题标题】:Using mock data: Typescript is not assignable to type使用模拟数据:Typescript 不可分配给类型
【发布时间】:2021-02-24 07:45:02
【问题描述】:

我是 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;
    }
  }

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

【问题讨论】:

  • 该错误应该包含一条消息,说明为什么它通常不能按照“缺少参数 Foo”之类的方式分配。
  • 你说得对,谢谢。我会将错误消息的缺失部分添加到帖子中。

标签: angular typescript


【解决方案1】:

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

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

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

  public childCategories: Category[] = [];

【讨论】:

  • 就是这样 - 谢谢。之前的评论者提醒我注意其他错误消息,我已经用这些更新了原始帖子。非常感谢。
猜你喜欢
  • 2022-08-23
  • 2021-10-17
  • 2020-03-26
  • 2018-09-19
  • 1970-01-01
  • 2023-01-18
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多