Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

typescript - Custom Angular type is not assignable to type NgIterable

Since I'm new to Angular I've learned about types and interfaces today. So what I did is I improved my code by coding a custom interface instead of a direct type declaration:

@Input()
imageWidgets: ImageWidget;

My interface:

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

This is what I pass to the component via the input variable:

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

Now inside the receiving component I'm doing an ngFor:

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

... but since I've introduced my interfaces, I'm getting this error:

Type ImageWidget is not assignable to type (ImageWidget & NgIterable<{routerLink: string, imageSrc: string, title: string}>) | undefined | null

I really have no idea why this happens but when I do this here, the error is gone:

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

I've searched a lot but I'm unable to remote this error message. What am I doing wrong here?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are super close! You are looking for this:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...