Angular 9类型错误:any[] | ReceiptResponse无法赋值给ReceiptResponse
解决Type 'any[] | ReceiptResponse' is not assignable to type 'ReceiptResponse'错误
咱们先揪出问题的根源:你在调用getPagedReceipts时,通过catchError(() => of([]))返回了一个空数组,但你的服务方法原本返回的是Observable<ReceiptResponse>类型。这就导致整个Observable的类型变成了Observable<ReceiptResponse | any[]>——也就是说,订阅时可能拿到的是ReceiptResponse对象,也可能是一个数组,而你把它赋值给明确声明为ReceiptResponse类型的this.receiptsResponse,TypeScript自然会抛出类型不兼容的错误。
解决方案:让catchError返回同类型的对象
既然你的业务逻辑后续要访问receiptsResponse.items,显然错误时返回数组是不合适的,正确的做法是返回一个符合ReceiptResponse结构的“空对象”,这样整个Observable的类型就能保持一致。
方法1:直接创建空的ReceiptResponse实例
修改调用代码里的catchError部分:
public receiptsResponse: ReceiptResponse; this.receiptService.getPagedReceipts(filter, sortOrder, sortColumn, pageIndex, pageSize).pipe( catchError(() => of(new ReceiptResponse(0, [], '', 0, '', 0))), finalize(() => this.loadingSubject.next(false)) ).subscribe(receiptsResponse => { this.receiptsResponse = receiptsResponse; this.receipts = this.receiptsResponse.items; console.log(this.receiptsResponse); this.receiptsSubject.next(this.receipts); });
方法2:给ReceiptResponse添加静态方法(更优雅)
在你的ReceiptResponse类里添加一个静态方法,用来生成默认的空对象,让代码更整洁:
import {Receipt} from './receipt'; export class ReceiptResponse { public itemCount: number; public items: Receipt[]; public next: string; public pageCount: number; public previous: string; public totalItems: number; constructor( itemCount?: number, items?: Receipt[], next?: string, pageCount?: number, previous?: string, totalItems?: number ) { this.itemCount = itemCount; this.items = items; this.pageCount = pageCount; this.next = next; this.previous = previous; this.totalItems = totalItems; } // 添加静态方法生成空对象 static empty(): ReceiptResponse { return new ReceiptResponse(0, [], '', 0, '', 0); } }
然后调用时就可以简化成:
catchError(() => of(ReceiptResponse.empty()))
为什么不能返回数组?
如果你坚持在错误时返回数组,那你需要把receiptsResponse的类型改成ReceiptResponse | any[],但这样后续访问this.receiptsResponse.items时会因为类型不确定而报错——因为数组并没有items属性,所以这种方案完全不符合你的业务需求。
内容的提问来源于stack exchange,提问作者ctilley79
相关产品推荐
相关产品推荐

