use-immer icon indicating copy to clipboard operation
use-immer copied to clipboard

Typescript error when using classes with private properties

Open dmm9 opened this issue 1 year ago • 0 comments

useImmerReducer() shows a type error when using classes with private properties:

class ClassWithPrivates {
  private readonly pa: string;
  private pb: boolean;
  private pmethod() {...}
  ...
}

interface myState {
  items: ClassWithPrivates[]
}
interface myAction {
  type: string;
  ...
}

function reducer(draft: myState, action: myAction) { // <-- Also 'draft: Draft<myState>' won't work
  switch (action.type) {
  ...
  }
}

export function myComponent() {
  const [state, dispatch] = useImmerReducer(reducer, initialValues);  // <-- Error in 'reducer'
  return (...)
}

The error:

Argument of type '(draft: myState, action: myAction) => myState' is not assignable to parameter of type 'ImmerReducer<myState, myAction>'.
  Types of parameters 'draft' and 'draftState' are incompatible.
    Type 'WritableDraft<myState>' is not assignable to type 'myState'.
      Types of property 'items' are incompatible.
        Type 'WritableDraft<ClassWithPrivates>' is missing the following properties from type 'ClassWithPrivates': pa, pb, pmethod ts(2345)

dmm9 avatar Aug 30 '24 10:08 dmm9