【问题标题】:Custom Angular type is not assignable to type NgIterable自定义 Angular 类型不可分配给类型 NgIterable
【发布时间】:2021-04-16 15:04:12
【问题描述】:

由于我是 Angular 新手,所以我今天学习了类型和接口。所以我所做的是通过编写自定义接口而不是直接类型声明来改进我的代码:

@Input()
imageWidgets: ImageWidget;

我的界面:

export interface ImageWidget {
  [index: number]: {
    routerLink: string,
    imageSrc: string,
    title: string
  }
}

这是我通过输入变量传递给组件的:

topics: ImageWidget       = [
  {
    imageSrc  : './assets/images/solutions.jpeg',
    title     : 'Solutions',
    routerLink: '/solutions'
  }
];

现在在接收组件中我正在做一个ngFor

<div *ngFor="let imageWidget of imageWidgets"></div>

...但是由于我已经介绍了我的接口,所以我收到了这个错误:

类型 ImageWidget 不可分配给类型(ImageWidget & NgIterable) | 未定义 |空

我真的不知道为什么会发生这种情况,但是当我在这里执行此操作时,错误消失了:

@Input()
imageWidgets: ImageWidget | NgIterable<any>;

我进行了很多搜索,但无法远程发送此错误消息。我在这里做错了什么?

【问题讨论】:

    标签: angular typescript types interface


    【解决方案1】:

    你超级亲密!你正在寻找这个:

    export interface ImageWidget {
        routerLink: string,
        imageSrc: string,
        title: string
    }
    
    @Input()
    imageWidgets: ImageWidget[]; // or could do Array<ImageWidget>;
    
    

    https://www.typescriptlang.org/docs/handbook/basic-types.html#array

    【讨论】:

    • 哦,不,我的界面有点太深了,但感谢您为我指明了正确的方向。现在错误消失了。
    猜你喜欢
    • 2017-10-01
    • 2021-08-15
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 2022-07-28
    • 2021-07-02
    相关资源
    最近更新 更多