类型 'Listing | undefined' 不可分配给类型 'Listing'。类型 'undefined' 不可分配给类型 'Listing'

Type 'Listing | undefined' is not assignable to type 'Listing'. Type 'undefined' is not assignable to type 'Listing'

您好,在我的项目中寻求帮助 问题是,我正在为一个错误而苦苦挣扎 https://github.com/abhijitutkarsh/buyandsell/blob/main/src/app/listing-detail-page/listing-detail-page.component.ts 上面 link 的代码库在编译时显示错误

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);

基本上是关于显示假数据的代码-data.ts。在这里,我从路由器 url 获取 ID。只是卡在这里。问题有点小,无法识别

当找不到结果时,find 可能会 return undefined。 您可以将 undefined 添加到列表类型中:

  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);
  }

或者查看是否有结果:

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