left click
left click

Reputation: 894

How to fix TypeScript error occurs when call takeEvery() in redux-saga?

import { createAction, handleActions } from 'redux-actions';
import { delay } from 'redux-saga';
import { all, put, takeEvery } from 'redux-saga/effects';

export const action_creators = {
    get_action_of_set_number: createAction<{ number:number }>('set_number'),
    get_action_of_set_number_async: createAction<{ number:number }>('set_number_async')
};

const state = {
    number: 0
}

function* set_number_async(action: { payload: { number:number } }) {
    yield delay(1000);
    yield put(action_creators.get_action_of_set_number(action.payload));
}

export function* saga(action) {
    yield all([takeEvery('set_number_async', set_number_async)]);
    *** Error message : Argument of type '"set_number_async"' is not assignable
    *** to parameter of type 'Channel<{ payload: { number:number; }; }>'.
}

export default handleActions({
    set_number: (state, action) => {
        const new_number = action.payload!.number;
        return { ...state, number:new_number };
    }
}, state);

full example : https://codesandbox.io/s/zry4vl2ymx (Other type definitions are omitted for convenience.)

I don't know what I did wrong. If you know what is problem and how to solve it, please help with soving the problem. Thanks! :)

Upvotes: 4

Views: 4311

Answers (1)

starwed
starwed

Reputation: 2607

When I ran into this issue, it was because my saga didn't actually have an action as it's argument -- I think you're running into the same thing.

In takeEvery('set_number_async', set_number_async), the method set_number_async's argument doesn't have a type property, which means it is not shaped like the Action type. (Remember that types in typescript are duck/structural -- they only really care about what properties a type has.)

If I change the signature by adding a type property, the example compiles:

function* set_number_async(action: { payload: { number:number }, type:string }) {
    yield delay(1000);
    yield put(action_creators.get_action_of_set_number(action.payload));
}

Upvotes: 11

Related Questions