Observable.forkJoin() TS2322 error after updating to TypeScript 2.4.1 and Rxjs 5.4.2

给你一囗甜甜゛ 提交于 2020-01-24 14:14:25

问题


In our angular 4.2.4 application, we use RxJS's Observable.forkJoin in a number of places to return heterogeneous types.

For example:

private fleet: Aircraft[];
private contractList: string[];

Observable.forkJoin([
  this.fleetService.getFleet(),
  this.fleetService.getContractList()
]).subscribe(
  next => {
    this.fleet = results[0];
    this.contractList = results[1];
  },
  error => console.error
);

with the following service signatures:

getFleet(): Observable<Aircraft[]> { ... }
getContractList(): Observable<string[]> { ... }

After updating to TypeScript 2.4.1, tsc now complains with the following errors for this.contractList:

ERROR in ./app/fleet/fleetComponent.ts (xx,xx): error TS2322: Type 'Aircraft[]' is not assignable to type 'string[]'.

But I'm not trying to assign an Aircraft[] to a string[].

The same is true for all the other Observable.forkJoin we implement: all elements in result[] are treated as though they were the same type as result[0].

It seems very similar to the problem in Error with Actions observable in @ngrx/effects using TypeScript 2.4.1 but adding "noStrictGenericChecks": true, to tsconfig.js' "compilerOptions" did not solve the problem.

Why is this happening? How can I fix this?


回答1:


You are probably seeing the increased enforcement from the Typescript compiler on generics, the side-effect being that forkJoin doesn't have a tuple overloads.

Removing the array notation from the parameter list to forkJoin should work, however:

Observable.forkJoin(
  this.fleetService.getFleet(),
  this.fleetService.getContractList()
).subscribe(
  next => {
    this.fleet = results[0];
    this.contractList = results[1];
  },
  error => console.error
);



回答2:


Note: I think it's better to use combineLatest as combineLatest fetch and return data as soon as available but forkJoin will wait until last chain command executes.



来源:https://stackoverflow.com/questions/45020250/observable-forkjoin-ts2322-error-after-updating-to-typescript-2-4-1-and-rxjs-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!