NgRX effects - Type 'Observable' is not assignable to type 'Observable'

前端 未结 9 1120
你的背包
你的背包 2020-12-16 10:12

While working with NgRX 8 my colleagues and me are frequently facing a weird error message when implementing the effects.

Type \'Observable

9条回答
  •  忘掉有多难
    2020-12-16 10:39

    I ran into a similar issue today (same error message) and it was because TypeScript couldn't infer correctly the return type of Array#flatMap. I assume it will be the same for Array#map, RxJS#map or any array that has not been explicitly typed.

    Here is the code that crashed :

    this.actions$.pipe(
        ofType(ActionType),
        switchMap((action) => {
            return action.cart.flatMap((cartItem: CartItem) => {
                if (x) {
                    return [
                        ActionCreator1(params1),
                        ActionCreator2(params2)
                    ];
                } else {
                    return [];
                }
            }
        })
    )
    

    So I got the same error message :

    Type 'Observable' is not assignable to type 'Observable | ((...args: any[]) => Observable)'

    To fix it, I just had to tell TypeScript that my mapping function returned an array of Action :

    import { Action } from '@ngrx/store';
    ...
        switchMap((action) => {
            return action.cart.flatMap((cartItem: CartItem) : Action[] => {
    ...
    

    Also, typing with Action[] is safer that with any !

提交回复
热议问题