forked from immerjs/immer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
produce.ts
775 lines (690 loc) · 16.3 KB
/
produce.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
import {assert, _} from "spec.ts"
import produce, {
produce as produce2,
applyPatches,
Patch,
nothing,
Draft,
Immutable,
enableAllPlugins,
Immer
} from "../src/immer"
enableAllPlugins()
interface State {
readonly num: number
readonly foo?: string
bar: string
readonly baz: {
readonly x: number
readonly y: number
}
readonly arr: ReadonlyArray<{readonly value: string}>
readonly arr2: {readonly value: string}[]
}
const state: State = {
num: 0,
bar: "foo",
baz: {
x: 1,
y: 2
},
arr: [{value: "asdf"}],
arr2: [{value: "asdf"}]
}
const expectedState: State = {
num: 1,
foo: "bar",
bar: "foo",
baz: {
x: 2,
y: 3
},
arr: [{value: "foo"}, {value: "asf"}],
arr2: [{value: "foo"}, {value: "asf"}]
}
it("can update readonly state via standard api", () => {
const newState = produce(state, draft => {
draft.num++
draft.foo = "bar"
draft.bar = "foo"
draft.baz.x++
draft.baz.y++
draft.arr[0].value = "foo"
draft.arr.push({value: "asf"})
draft.arr2[0].value = "foo"
draft.arr2.push({value: "asf"})
})
assert(newState, _ as State)
})
// NOTE: only when the function type is inferred
it("can infer state type from default state", () => {
type State = {readonly a: number}
type Recipe = (state?: State | undefined) => State
let foo = produce((_: any) => {}, _ as State)
assert(foo, _ as Recipe)
})
it("can infer state type from recipe function", () => {
type A = {readonly a: string}
type B = {readonly b: string}
type State = A | B
type Recipe = (state: State) => State
let foo = produce((draft: State) => {
assert(draft, _ as State)
if (Math.random() > 0.5) return {a: "test"}
else return {b: "boe"}
})
const x = foo({a: ""})
const y = foo({b: ""})
assert(foo, _ as Recipe)
})
it("can infer state type from recipe function with arguments", () => {
type State = {readonly a: string} | {readonly b: string}
type Recipe = (state: State, x: number) => State
let foo = produce<State, [number]>((draft, x) => {
assert(draft, _ as Draft<State>)
assert(x, _ as number)
})
assert(foo, _ as Recipe)
})
it("can infer state type from recipe function with arguments and initial state", () => {
type State = {readonly a: string} | {readonly b: string}
type Recipe = (state: State | undefined, x: number) => State
let foo = produce((draft: Draft<State>, x: number) => {}, _ as State)
assert(foo, _ as Recipe)
})
it("cannot infer state type when the function type and default state are missing", () => {
type Recipe = <S extends any>(state: S) => S
const foo = produce((_: any) => {})
// @ts-expect-error
assert(foo, _ as Recipe)
})
it("can update readonly state via curried api", () => {
const newState = produce((draft: Draft<State>) => {
draft.num++
draft.foo = "bar"
draft.bar = "foo"
draft.baz.x++
draft.baz.y++
draft.arr[0].value = "foo"
draft.arr.push({value: "asf"})
draft.arr2[0].value = "foo"
draft.arr2.push({value: "asf"})
})(state)
expect(newState).not.toBe(state)
expect(newState).toEqual(expectedState)
})
it("can update use the non-default export", () => {
const newState = produce2((draft: Draft<State>) => {
draft.num++
draft.foo = "bar"
draft.bar = "foo"
draft.baz.x++
draft.baz.y++
draft.arr[0].value = "foo"
draft.arr.push({value: "asf"})
draft.arr2[0].value = "foo"
draft.arr2.push({value: "asf"})
})(state)
expect(newState).not.toBe(state)
expect(newState).toEqual(expectedState)
})
it("can apply patches", () => {
let patches: Patch[] = []
produce(
{x: 3},
d => {
d.x++
},
p => {
patches = p
}
)
expect(applyPatches({}, patches)).toEqual({x: 4})
})
describe("curried producer", () => {
it("supports rest parameters", () => {
type State = {readonly a: 1}
// No initial state:
{
type Recipe = (state: State, a: number, b: number) => State
let foo = produce((s: State, a: number, b: number) => {})
assert(foo, _ as Recipe)
foo(_ as State, 1, 2)
}
// Using argument parameters:
{
type Recipe = (state: Immutable<State>, ...rest: number[]) => Draft<State>
let woo = produce((state: Draft<State>, ...args: number[]) => {})
assert(woo, _ as Recipe)
woo(_ as State, 1, 2)
}
// With initial state:
{
type Recipe = (state?: State | undefined, ...rest: number[]) => State
let bar = produce((state: Draft<State>, ...args: number[]) => {},
_ as State)
assert(bar, _ as Recipe)
bar(_ as State, 1, 2)
bar(_ as State)
bar()
}
// When args is a tuple:
{
type Recipe = (
state: State | undefined,
first: string,
...rest: number[]
) => State
let tup = produce(
(state: Draft<State>, ...args: [string, ...number[]]) => {},
_ as State
)
assert(tup, _ as Recipe)
tup({a: 1}, "", 2)
tup(undefined, "", 2)
}
})
it("can be passed a readonly array", () => {
// No initial state:
{
let foo = produce((state: string[]) => {})
assert(foo, _ as (state: readonly string[]) => string[])
foo([] as ReadonlyArray<string>)
}
// With initial state:
{
let bar = produce(() => {}, [] as ReadonlyArray<string>)
assert(
bar,
_ as (state?: readonly string[] | undefined) => readonly string[]
)
bar([] as ReadonlyArray<string>)
bar(undefined)
bar()
}
})
})
it("works with return type of: number", () => {
let base = {a: 0} as {a: number}
{
if (Math.random() === 100) {
// @ts-expect-error, this return accidentally a number, this is probably a dev error!
let result = produce(base, draft => draft.a++)
}
}
{
let result = produce(base, draft => void draft.a++)
assert(result, _ as {a: number})
}
})
it("can return an object type that is identical to the base type", () => {
let base = {a: 0} as {a: number}
let result = produce(base, draft => {
return draft.a < 0 ? {a: 0} : undefined
})
assert(result, _ as {a: number})
})
it("can NOT return an object type that is _not_ assignable to the base type", () => {
let base = {a: 0} as {a: number}
// @ts-expect-error
let result = produce(base, draft => {
return draft.a < 0 ? {a: true} : undefined
})
})
it("does not enforce immutability at the type level", () => {
let result = produce([] as any[], draft => {
draft.push(1)
})
assert(result, _ as any[])
})
it("can produce an undefined value", () => {
type State = {readonly a: number} | undefined
const base = {a: 0} as State
// Return only nothing.
let result = produce(base, _ => nothing)
assert(result, _ as State)
// Return maybe nothing.
let result2 = produce(base, draft => {
if (draft?.a ?? 0 > 0) return nothing
})
assert(result2, _ as State)
})
it("can return the draft itself", () => {
let base = _ as {readonly a: number}
let result = produce(base, draft => draft)
assert(result, _ as {readonly a: number})
})
it("can return a promise", () => {
type Base = {readonly a: number}
let base = {a: 0} as Base
// Return a promise only.
let res1 = produce(base, draft => {
return Promise.resolve(draft)
})
assert(res1, _ as Promise<Base>)
// Return a promise or undefined.
let res2 = produce(base, draft => {
return Promise.resolve()
})
assert(res2, _ as Promise<Base>)
})
it("works with `void` hack", () => {
let base = {a: 0} as {readonly a: number}
let copy = produce(base, s => void s.a++)
assert(copy, base)
})
it("works with generic parameters", () => {
let insert = <T>(array: readonly T[], index: number, elem: T) => {
// Need explicit cast on draft as T[] is wider than readonly T[]
return produce(array, (draft: T[]) => {
draft.push(elem)
draft.splice(index, 0, elem)
draft.concat([elem])
})
}
let val: {readonly a: ReadonlyArray<number>} = {a: []} as any
let arr: ReadonlyArray<typeof val> = [] as any
insert(arr, 0, val)
})
it("can work with non-readonly base types", () => {
const state = {
price: 10,
todos: [
{
title: "test",
done: false
}
]
}
type State = typeof state
const newState = produce(state, draft => {
draft.price += 5
draft.todos.push({
title: "hi",
done: true
})
})
assert(newState, _ as State)
const reducer = (draft: State) => {
draft.price += 5
draft.todos.push({
title: "hi",
done: true
})
}
// base case for with-initial-state
const newState4 = produce(reducer, state)(state)
assert(newState4, _ as State)
// no argument case, in that case, immutable version recipe first arg will be inferred
const newState5 = produce(reducer, state)()
assert(newState5, _ as State)
// we can force the return type of the reducer by casting the initial state
const newState3 = produce(reducer, state as State)()
assert(newState3, _ as State)
})
it("can work with readonly base types", () => {
type State = {
readonly price: number
readonly todos: readonly {
readonly title: string
readonly done: boolean
}[]
}
const state: State = {
price: 10,
todos: [
{
title: "test",
done: false
}
]
}
const newState = produce(state, draft => {
draft.price + 5
draft.todos.push({
title: "hi",
done: true
})
})
assert(newState, _ as State)
assert(newState, _ as Immutable<State>) // cause that is the same!
const reducer = (draft: Draft<State>) => {
draft.price += 5
draft.todos.push({
title: "hi",
done: true
})
}
const newState2: State = produce(reducer)(state)
assert(newState2, _ as State)
// base case for with-initial-state
const newState4 = produce(reducer, state)(state)
assert(newState4, _ as State)
// no argument case, in that case, immutable version recipe first arg will be inferred
const newState5 = produce(reducer, state)()
assert(newState5, _ as State)
// we can force the return type of the reducer by casting initial argument
const newState3 = produce(reducer, state as State)()
assert(newState3, _ as State)
})
it("works with generic array", () => {
const append = <T>(queue: T[], item: T) =>
// T[] is needed here v. Too bad.
produce(queue, (queueDraft: T[]) => {
queueDraft.push(item)
})
const queueBefore = [1, 2, 3]
const queueAfter = append(queueBefore, 4)
expect(queueAfter).toEqual([1, 2, 3, 4])
expect(queueBefore).toEqual([1, 2, 3])
})
it("works with Map and Set", () => {
const m = new Map([["a", {x: 1}]])
const s = new Set([{x: 2}])
const res1 = produce(m, draft => {
assert(draft, _ as Map<string, {x: number}>)
})
assert(res1, _ as Map<string, {x: number}>)
const res2 = produce(s, draft => {
assert(draft, _ as Set<{x: number}>)
})
assert(res2, _ as Set<{x: number}>)
})
it("works with readonly Map and Set", () => {
type S = {readonly x: number}
const m: ReadonlyMap<string, S> = new Map([["a", {x: 1}]])
const s: ReadonlySet<S> = new Set([{x: 2}])
const res1 = produce(m, (draft: Draft<Map<string, S>>) => {
assert(draft, _ as Map<string, {x: number}>)
})
assert(res1, _ as ReadonlyMap<string, {readonly x: number}>)
const res2 = produce(s, (draft: Draft<Set<S>>) => {
assert(draft, _ as Set<{x: number}>)
})
assert(res2, _ as ReadonlySet<{readonly x: number}>)
})
it("works with ReadonlyMap and ReadonlySet", () => {
type S = {readonly x: number}
const m: ReadonlyMap<string, S> = new Map([["a", {x: 1}]])
const s: ReadonlySet<S> = new Set([{x: 2}])
const res1 = produce(m, (draft: Draft<Map<string, S>>) => {
assert(draft, _ as Map<string, {x: number}>)
})
assert(res1, _ as ReadonlyMap<string, {readonly x: number}>)
const res2 = produce(s, (draft: Draft<Set<S>>) => {
assert(draft, _ as Set<{x: number}>)
})
assert(res2, _ as ReadonlySet<{readonly x: number}>)
})
it("shows error in production if called incorrectly", () => {
expect(() => {
debugger
produce(null as any)
}).toThrow(
(global as any).USES_BUILD
? "[Immer] minified error nr: 6"
: "[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()
})
it("infers draft, #720", () => {
function nextNumberCalculator(fn: (base: number) => number) {
// noop
}
const res2 = nextNumberCalculator(
produce(draft => {
// @ts-expect-error
let x: string = draft
return draft + 1
})
)
const res = nextNumberCalculator(
produce(draft => {
// @ts-expect-error
let x: string = draft
// return draft + 1;
return undefined
})
)
})
it("infers draft, #720 - 2", () => {
function useState<S>(
initialState: S | (() => S)
): [S, Dispatch<SetStateAction<S>>] {
return [initialState, function() {}] as any
}
type Dispatch<A> = (value: A) => void
type SetStateAction<S> = S | ((prevState: S) => S)
const [n, setN] = useState({x: 3})
setN(
produce(draft => {
// @ts-expect-error
draft.y = 4
draft.x = 5
return draft
})
)
setN(
produce(draft => {
// @ts-expect-error
draft.y = 4
draft.x = 5
// return draft + 1;
return undefined
})
)
setN(
produce(draft => {
return {y: 3} as const
})
)
})
it("infers draft, #720 - 3", () => {
function useState<S>(
initialState: S | (() => S)
): [S, Dispatch<SetStateAction<S>>] {
return [initialState, function() {}] as any
}
type Dispatch<A> = (value: A) => void
type SetStateAction<S> = S | ((prevState: S) => S)
const [n, setN] = useState({x: 3} as {readonly x: number})
setN(
produce(draft => {
// @ts-expect-error
draft.y = 4
draft.x = 5
return draft
})
)
setN(
produce(draft => {
// @ts-expect-error
draft.y = 4
draft.x = 5
// return draft + 1;
return undefined
})
)
setN(
produce(draft => {
return {y: 3} as const
})
)
})
it("infers curried", () => {
type Todo = {title: string}
{
const fn = produce((draft: Todo) => {
let x: string = draft.title
})
fn({title: "test"})
// @ts-expect-error
fn(3)
}
{
const fn = produce((draft: Todo) => {
let x: string = draft.title
return draft
})
fn({title: "test"})
// @ts-expect-error
fn(3)
}
})
it("infers async curried", async () => {
type Todo = {title: string}
{
const fn = produce(async (draft: Todo) => {
let x: string = draft.title
})
const res = await fn({title: "test"})
// @ts-expect-error
fn(3)
assert(res, _ as Todo)
}
{
const fn = produce(async (draft: Todo) => {
let x: string = draft.title
return draft
})
const res = await fn({title: "test"})
// @ts-expect-error
fn(3)
assert(res, _ as Todo)
}
})
{
type State = {count: number}
type ROState = Immutable<State>
const base: any = {count: 0}
const res3 = produce({a: 123}, s => {
return s as any
})
{
// basic
const res = produce(base as State, draft => {
draft.count++
})
assert(res, _ as State)
}
{
// basic
const res = produce<State>(base, draft => {
draft.count++
})
assert(res, _ as State)
}
{
// basic
const res = produce(base as ROState, draft => {
draft.count++
})
assert(res, _ as ROState)
}
{
// curried
const f = produce((state: State) => {
state.count++
})
assert(f, _ as (state: Immutable<State>) => State)
}
{
// curried
const f = produce((state: Draft<ROState>) => {
state.count++
})
assert(f, _ as (state: ROState) => State)
}
{
// curried
const f: (value: State) => State = produce(state => {
state.count++
})
}
{
// curried
const f: (value: ROState) => ROState = produce(state => {
state.count++
})
}
{
// curried initial
const f = produce(state => {
state.count++
}, _ as State)
assert(f, _ as (state?: State) => State)
}
{
// curried initial
const f = produce(state => {
state.count++
}, _ as ROState)
assert(f, _ as (state?: ROState) => ROState)
}
{
// curried
const f: (value: State) => State = produce(state => {
state.count++
}, base as ROState)
}
{
// curried
const f: (value: ROState) => ROState = produce(state => {
state.count++
}, base as ROState)
}
{
// nothing allowed
const res = produce(base as State | undefined, draft => {
return nothing
})
assert(res, _ as State | undefined)
}
{
// as any
const res = produce(base as State, draft => {
return nothing as any
})
assert(res, _ as State)
}
{
// nothing not allowed
// @ts-expect-error
produce(base as State, draft => {
return nothing
})
}
{
const f = produce((draft: State) => {})
const n = f(base as State)
assert(n, _ as State)
}
{
const f = produce((draft: Draft<ROState>) => {
draft.count++
})
const n = f(base as ROState)
assert(n, _ as State)
}
{
// explictly use generic
const f = produce<ROState>(draft => {
draft.count++
})
const n = f(base as ROState)
assert(n, _ as ROState) // yay!
}
}