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

the Draft<T> could not use the keyof T type

Rey-Wang opened this issue · comments

you can see an code example here:
code sandbox

function ChangeState<T extends Record<string, any>, M extends keyof T>(
  state: T,
  field: M,
  value: T[M]
) {
  return produce(state, (draftState) => {
    draftState[field] = value;
    // Type 'M' cannot be used to index type 'Draft<T>'
  });
}

the keyof T should be used by Draft<T>

commented

I'm sorry but how does castDraft help here? draftState is already of the type Draft<T> using the cast would produce Draft<Draft<T>>.

I have a similar problem:

function ChangeStringState<M extends string>(
  state: Record<M, string>,
  field: M,
  value: string,
) {
  return produce(state, (draftState) => {
    draftState[field] = value;
    // Type 'M' cannot be used to index type 'Draft<Record<M, string>>'
  });
}

Yeah same here, is there a way to use a generic keyof M parameter to index the Draft type?