Search code examples
typescriptredux-toolkit

Typescript how to use optional chaining


Why an i getting an error on this value assignment;

state.user?.weight.budget = budget;

enter image description here

I have tried a couple this like this

(state.user?.weight.budget ?? 0) = budget;

That doesn't work either. What an I doing wrong. I dont get it

Thank you in advance.


Solution

  • Optional chaining does not support assignment. The feature was discussed but they decided it was out of scope for the initial proposal and that it might be implemented "later". See this comment in particular.

    Your latter example, (state.user?.weight.budget ?? 0) = budget; also won't work because not only are you trying to do an optional chaining assignment, but you're also trying to assign to an expression that is possibly not a variable or the property of a variable (0 = budget?).

    For now, the only way to do an assignment in the presence of possibly-undefined user property is via control flow without optional chaining, like this:

    if (state.user != null) state.user.weight.budget = budget;
    

    or some equivalent test-and-maybe-assign code.

    Playground link to code