【问题标题】:Why Type zzz is not assignable to type (zzz & NgIterable<xxx>) | undefined | null为什么类型 zzz 不能分配给类型 (zzz & NgIterable<xxx>) |未定义 |无效的
【发布时间】:2020-09-19 22:47:56
【问题描述】:

在 Angular 9 中为什么我会收到此消息: 类型项目不可分配给类型 (Items & NgIterable) |未定义 |空

模型是正确的。我的数据没有错误。 该代码有效,但我仍然收到此打字稿警告。

myData 的模型如下所示:

interface Item {
  url: string;
  label: string;
}

export interface Items {
  [key:number]: Item ;
}

我的 HTML:

<ng-container *ngFor="let card of myData"><!-- here I get the warning -->
some content
</ng-container>

添加:我忘记添加示例数据以使这一点更清楚。 它是一个这样的数组:

[
    {
      url: 'todo',
      label: 'Rekeningnummer'
    },
    {
      url: 'todo',
      label: 'Postadres'
    }] 

【问题讨论】:

  • 在 ng-container 下方,添加:
    {{myData | json}}
    。这应该告诉您该数据在模板中的实际外观。我敢打赌 myData 不是数组或其他可迭代的数据类型。
  • 我忘了添加示例数据以使这一点更清楚。它是一个数组:[ { url: 'todo', label: 'Rekeningnummer' }, { url: 'todo', label: 'Postadres' }]
  • 你是如何在你的 component.ts 中定义 myData 的?
  • myData: Items = DATAMOCK 并且 DATAMOCK 被定义为类型“Items”..

标签: angular typescript ngfor


【解决方案1】:

我通过使用类型 Item[] 而不是 Items 来修复它。

myData: Item[] = [...]

我读到 [key: string]: T 形式的索引可以被视为始终是可选的。所以看来我不能使用?使数组可能为空。

export interface Items {
  [key:number]?: Item ;
}

【讨论】:

    猜你喜欢
    • 2021-04-16
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 2021-02-07
    • 1970-01-01
    • 2022-11-14
    • 2021-08-15
    相关资源
    最近更新 更多