diff --git a/__tests__/produce.ts b/__tests__/produce.ts index c927e1ad..c0fb74ed 100644 --- a/__tests__/produce.ts +++ b/__tests__/produce.ts @@ -6,7 +6,8 @@ import produce, { nothing, Draft, Immutable, - enableAllPlugins + enableAllPlugins, + Immer } from "../src/immer" enableAllPlugins() @@ -477,3 +478,19 @@ it("shows error in production if called incorrectly", () => { : "[Immer] The first or second argument to `produce` must be a function" ) }) + +it("#749 types Immer", () => { + const t = { + x: 3 + } + + const immer = new Immer() + const z = immer.produce(t, d => { + d.x++ + // @ts-expect-error + d.y = 0 + }) + expect(z.x).toBe(4) + // @ts-expect-error + expect(z.z).toBeUndefined() +}) diff --git a/src/core/immerClass.ts b/src/core/immerClass.ts index f98d3756..1818e909 100644 --- a/src/core/immerClass.ts +++ b/src/core/immerClass.ts @@ -42,8 +42,6 @@ export class Immer implements ProducersFns { this.setUseProxies(config!.useProxies) if (typeof config?.autoFreeze === "boolean") this.setAutoFreeze(config!.autoFreeze) - this.produce = this.produce.bind(this) - this.produceWithPatches = this.produceWithPatches.bind(this) } /** @@ -65,7 +63,7 @@ export class Immer implements ProducersFns { * @param {Function} patchListener - optional function that will be called with all the patches produced here * @returns {any} a new state, or the initial state if nothing was modified */ - produce(base: any, recipe?: any, patchListener?: any) { + produce: IProduce = (base: any, recipe?: any, patchListener?: any) => { // curried invocation if (typeof base === "function" && typeof recipe !== "function") { const defaultBase = recipe @@ -123,7 +121,11 @@ export class Immer implements ProducersFns { } else die(21, base) } - produceWithPatches(arg1: any, arg2?: any, arg3?: any): any { + produceWithPatches: IProduceWithPatches = ( + arg1: any, + arg2?: any, + arg3?: any + ): any => { if (typeof arg1 === "function") { return (state: any, ...args: any[]) => this.produceWithPatches(state, (draft: any) => arg1(draft, ...args))