Skip to content

Commit

Permalink
fix: new Immer().produce now has the same type as produce. Fixes #749
Browse files Browse the repository at this point in the history
  • Loading branch information
mweststrate committed Mar 18, 2021
1 parent e3dfdcd commit f8b77d1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
19 changes: 18 additions & 1 deletion __tests__/produce.ts
Expand Up @@ -6,7 +6,8 @@ import produce, {
nothing,
Draft,
Immutable,
enableAllPlugins
enableAllPlugins,
Immer
} from "../src/immer"

enableAllPlugins()
Expand Down Expand Up @@ -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()
})
10 changes: 6 additions & 4 deletions src/core/immerClass.ts
Expand Up @@ -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)
}

/**
Expand All @@ -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
Expand Down Expand Up @@ -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))
Expand Down

0 comments on commit f8b77d1

Please sign in to comment.