Hi seeking help in my project The thing is, I am struggling with an error https://github.com/abhijitutkarsh/buyandsell/blob/main/src/app/listing-detail-page/listing-detail-page.component.ts above link has the code base when compiling it is showing an error saying
src/app/listing-detail-page/listing-detail-page.component.ts:20:5 - error TS2322: Type 'Listing | undefined' is not assignable to type 'Listing'.
Type 'undefined' is not assignable to type 'Listing'.
20 this.listing = fakeListings.find(listing => listing.id === id);
Basically the code about showing data from the fake-data.ts. here i am getting the id from the router url. just stuck here. The issue is kind of minor, not able to identify
CodePudding user response:
It is possible for find to return undefined when it did not find a result. You can add undefined to the listing type:
listing: Listing | undefined;
constructor(
private route: ActivatedRoute,
) { }
ngOnInit(): void {
const id = this.route.snapshot.paramMap.get('id');
this.listing = fakeListings.find(listing => listing.id === id);
}
Or check if there is a result:
listing: Listing;
constructor(
private route: ActivatedRoute,
) { }
ngOnInit(): void {
const id = this.route.snapshot.paramMap.get('id');
const fakeListing = fakeListings.find(listing => listing.id === id);
if (fakeListing !== undefined){
this.listing = fakeListing;
}
}