immerjs / immer

Create the next immutable state by mutating the current one

Home Page:https://immerjs.github.io/immer/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is there a possibility to use immear as one-liner?

max-prtsr opened this issue Β· comments

πŸ™‹β€β™‚ Question

I personally don't like this code taking 3 lines instead of one

    const newRecords = produce(scheduleRecords, (draft) => {
      draft[index] = updatedRecord
    })

I would like to have

    const newRecords = produce(scheduleRecords, (draft) => draft[index] = updatedRecord)

but I got a TS error

TS2769: No overload matches this call.   
The last overload gave the following error.     
Type 'Partial<Record>' is not assignable to type 'ValidRecipeReturnType<WritableDraft<Partial<Record>>[]>'. 

Environment

v10.0.2
We only accept questions against the latest Immer version.

πŸ™‹β€β™‚ Question

I personally don't like this code taking 3 lines instead of one

    const newRecords = produce(scheduleRecords, (draft) => {
      draft[index] = updatedRecord
    })

I would like to have

    const newRecords = produce(scheduleRecords, (draft) => draft[index] = updatedRecord)

but I got a TS error

TS2769: No overload matches this call.   
The last overload gave the following error.     
Type 'Partial<Record>' is not assignable to type 'ValidRecipeReturnType<WritableDraft<Partial<Record>>[]>'. 

Environment

v10.0.2 We only accept questions against the latest Immer version.

@max-prtsr
Of course, you can achieve that with the comma operator of javascript. For instance:

import { produce } from "immer";

const defaultMySubState = {
  someString: "foo", 
}

const newRecords = produce(defaultMySubState, (draft) => (draft["someString"] = "updatedRecord", void 0))

But to have better readable codes, I will never use this shortcode in a team project πŸ˜‚. I think we should avoid it.

To clarify my previous message, no comma operator is needed here, since void can be used directly as operator. So it'd become:

const newRecords = produce(scheduleRecords, (draft) => void draft[index] = updatedRecord)