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

前端 未结 9 1089
你的背包
你的背包 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:38

    Actually you need to treat actions created by createAction as a function and call it to return the action object. Check this desc. So your of(addCommentFailed) should be of(addCommentFailed()).

    0 讨论(0)
  • 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<unknown>' is not assignable to type 'Observable<Action> | ((...args: any[]) => Observable<Action>)'

    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 !

    0 讨论(0)
  • 2020-12-16 10:39

    I struggled with this issue for a while only to find out at the end that VS code automatically imported Observable from some library instead of rxjs

    Hope this saves someone unnecessary head banging.

    0 讨论(0)
提交回复
热议问题