Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redux-actions createAction default parameters in payloadCreator function (typeScript)

if i generate an action as such:

export const updateParticularObjectValue = createAction(
    UPDATE_PARTICULAR_VALUE,
    (id: string, amount: number, reason: string = 'default') => { 
        return { id, value: amount, reason }; 
    },
);

for some reason my IDE (and indeed, my typescript compiler) is complaining that calling the action creator expects only two arguments when i pass the third explicitly. i would like the creator to take the third argument optionally... is there a way to do this using the redux-actions createAction function, or do i need to manually build the action creator?

P.S. -- also this syntax causes the same result:

export const updateParticularObjectValue = createAction(
    UPDATE_PARTICULAR_VALUE,
    (id: string, amount: number, reason?: string) => { 
        return { id, value: amount, reason: reason || 'default' }; 
    },
);

seems like making the third argument optional in any way does not translate in typescript -- it's treated as nonexistent and calls to the function forbid including it. is there a way around this?

P.P.S. -- if you can 'fool' the typescript compiler (in my case by defining the function interface in a component's Props type when using 'connect' in a react component) it works fine, it just doesn't pass the compiler's smell test when calling it explicitly -- seems there's no real reason this should occur.

P.P.P.S. -- at this point, i've found a workable solution. i am, however, still interested in why this is a limitation of createAction's typescript implementation and if there are any alternate solutions that would be better/smarter for this situation. a good explanation would be educational for myself and, likely, others.

like image 741
derelict Avatar asked Jun 03 '26 06:06

derelict


1 Answers

You can do something like this, using an arrow function return createAction function:

interface ActionProps {
    id: string;
    amount: number;
    reason: string;
}

export const updateParticularObjectValue = (props: ActionProps) => (createAction('UPDATE_PARTICULAR_VALUE', {
    id: props.id,
    value: props.amount,
    reason: props.reason
}));
like image 106
FisNaN Avatar answered Jun 05 '26 02:06

FisNaN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!