immerjs / immer

Create the next immutable state by mutating the current one
https://immerjs.github.io/immer/
MIT License
27.5k stars 850 forks source link

Property ... is missing in type WritableDraft<...> but required in type ... #1097

Closed Rennix09 closed 6 months ago

Rennix09 commented 6 months ago

🙋‍♂ Question

I got a type error when I tried to wrap a class instance that owns private fields. WhatI should I do?

Code Snippet

import { WritableDraft } from "immer/dist/internal";

class Frontend {
    private frameworks: string[] = ['React', 'Vue', 'Angular'];
}

const frontend: Frontend = {} as WritableDraft<Frontend>; 

Expect: The wrapped type is compatible to the original type

Actual: Property 'frameworks' is missing in type 'WritableDraft' but required in type 'Frontend'.ts(2741)

Rennix09 commented 6 months ago

Resolved this by defining an interface.

import { WritableDraft } from "immer/dist/internal";
interface IFrontend {
  ... // all the public members here
}

class Frontend implements IFrontend {
    private frameworks: string[] = ['React', 'Vue', 'Angular'];
}

const frontend: IFrontend = {} as WritableDraft<IFrontend>;