feat: general typing improvements for TS 3.7 and up
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by GitHub · parents 9f4711a, 69cbf56 · Browse files · 17 files·+558 added−232 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
17 files+558 added−232 removed
- tests:+233 added−4 removed
- other:+325 added−228 removed
Provenance
- Commit
f930ce1- Tree
ffc1cd7- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
9f4711a- Parent 2
69cbf56
17 files changed+558 added−232 removed
modified:__tests__/base.js+14 added
587 unmodified lines588 produce(map, d => {589 expect(d instanceof Map).toBeTruthy()590 })591 })592+593+ it("handles clear correctly", () => {594+ const map = new Map([595+ ["a", 1],596+ ["c", 3]597+ ])598+ const next = produce(map, draft => {599+ draft.delete("a")600+ draft.set("b", 2)601+ draft.set("c", 4)602+ draft.clear()603+ })604+ expect(next).toEqual(new Map())605+ })606 })607 608 describe("set drafts", () => {609 it("supports iteration", () => {1379 unmodified linesmodified:__tests__/draft.ts+42 added-1 removed
1 import {assert, _} from "spec.ts"2-import {Draft} from "../src/index"2+import produce, {Draft, castDraft, original} from "../src/index"3 4 // For checking if a type is assignable to its draft type (and vice versa)5 const toDraft: <T>(value: T) => Draft<T> = x => x as any6 const fromDraft: <T>(draft: Draft<T>) => T = x => x as any179 unmodified lines186 assert(toDraft(weak), weak)187 assert(fromDraft(toDraft(weak)), weak)188 }189 190+ // ReadonlyMap instance191+ {192+ let val: ReadonlyMap<any, any> = _193+ let draft: Map<any, any> = _194+ assert(toDraft(val), draft)195+ }196+197 // Set instance198 {199 let val: Set<any> = _200 assert(toDraft(val), val)4 unmodified lines205 assert(toDraft(weak), weak)206 assert(fromDraft(toDraft(weak)), weak)207 }208 209+ // ReadonlySet instance210+ {211+ let val: ReadonlySet<any> = _212+ let draft: Set<any> = _213+ assert(toDraft(val), draft)214+ }215+216 // Promise object217 {218 let val: Promise<any> = _219 assert(toDraft(val), val)82 unmodified lines302 }303 304 expect(true).toBe(true)305 })306+307+test("asDraft", () => {308+ type Todo = {readonly done: boolean}309+310+ type State = {311+ readonly finishedTodos: ReadonlyArray<Todo>312+ readonly unfinishedTodos: ReadonlyArray<Todo>313+ }314+315+ function markAllFinished(state: State) {316+ produce(state, draft => {317+ draft.finishedTodos = castDraft(state.unfinishedTodos)318+ })319+ }320+})321+322+test("#505 original", () => {323+ const baseState = {users: [{name: "Richie"}] as const}324+ const nextState = produce(baseState, draftState => {325+ original(draftState.users) === baseState.users326+ })327+})328+329+test("asDraft preserves a value", () => {330+ const x = {}331+ expect(castDraft(x)).toBe(x)332+})modified:__tests__/immutable.ts+58 added-1 removed
122345648 unmodified lines555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import {assert, _} from "spec.ts"import {Immutable} from "../src/index"import produce, {Immutable, castImmutable} from "../src/index"
test("types are ok", () => { // array in tuple {48 unmodified lines let val = _ as Immutable<{a: {b: string}}> assert(val, _ as {readonly a: {readonly b: string}}) }
// Map { let val = _ as Immutable<Map<string, string>> assert(val, _ as ReadonlyMap<string, string>) }
// Already immutable Map { let val = _ as Immutable<ReadonlyMap<string, string>> assert(val, _ as ReadonlyMap<string, string>) }
// object in Map { let val = _ as Immutable<Map<{a: string}, {b: string}>> assert(val, _ as ReadonlyMap<{readonly a: string}, {readonly b: string}>) }
// Set { let val = _ as Immutable<Set<string>> assert(val, _ as ReadonlySet<string>) }
// Already immutable Set { let val = _ as Immutable<ReadonlySet<string>> assert(val, _ as ReadonlySet<string>) }
// object in Set { let val = _ as Immutable<Set<{a: string}>> assert(val, _ as ReadonlySet<{readonly a: string}>) }
expect(true).toBe(true)})
test("#381 produce immutable state", () => { const someState = { todos: [ { done: false } ] }
const immutable = castImmutable(produce(someState, _draft => {})) assert( immutable, _ as {readonly todos: ReadonlyArray<{readonly done: boolean}>} )})
test("castImmutable preserves a value", () => { const x = {} expect(castImmutable(x)).toBe(x)})modified:__tests__/produce.ts+18 added-2 removed
436 unmodified lines437 const m = new Map<string, S>([["a", {x: 1}]])438 const s = new Set<S>([{x: 2}])439 440 const res1 = produce(m, (draft: Draft<Map<string, S>>) => {441- assert(draft, _ as Map<string, {readonly x: number}>) // TODO: drop readonly in TS 3.7441+ assert(draft, _ as Map<string, {x: number}>)442 })443 assert(res1, _ as Map<string, {readonly x: number}>)444 445 const res2 = produce(s, (draft: Draft<Set<S>>) => {446- assert(draft, _ as Set<{readonly x: number}>) // TODO: drop readonly in TS 3.7446+ assert(draft, _ as Set<{x: number}>)447 })448 assert(res2, _ as Set<{readonly x: number}>)449 })450+451+it("works with ReadonlyMap and ReadonlySet", () => {452+ type S = {readonly x: number}453+ const m: ReadonlyMap<string, S> = new Map([["a", {x: 1}]])454+ const s: ReadonlySet<S> = new Set([{x: 2}])455+456+ const res1 = produce(m, (draft: Draft<Map<string, S>>) => {457+ assert(draft, _ as Map<string, {x: number}>)458+ })459+ assert(res1, _ as ReadonlyMap<string, {readonly x: number}>)460+461+ const res2 = produce(s, (draft: Draft<Set<S>>) => {462+ assert(draft, _ as Set<{x: number}>)463+ })464+ assert(res2, _ as ReadonlySet<{readonly x: number}>)465+})added:__tests__/redux.ts+101 added
1+import {assert, _} from "spec.ts"2+import produce, {3+ produce as produce2,4+ applyPatches,5+ Patch,6+ nothing,7+ Draft,8+ Immutable9+} from "../src/"10+import * as redux from "redux"11+12+export interface State {13+ counter: number14+}15+16+export interface Action {17+ type: string18+ payload: number19+}20+21+export const initialState: State = {22+ counter: 023+}24+25+/// =============== Actions26+27+export function addToCounter(addNumber: number) {28+ return {29+ type: "ADD_TO_COUNTER",30+ payload: addNumber31+ }32+}33+34+export function subFromCounter(subNumber: number) {35+ return {36+ type: "SUB_FROM_COUNTER",37+ payload: subNumber38+ }39+}40+41+export const reduceCounterProducer = (42+ state: State = initialState,43+ action: Action44+) =>45+ produce(state, draftState => {46+ switch (action.type) {47+ case "ADD_TO_COUNTER":48+ draftState.counter += action.payload49+ break50+ case "SUB_FROM_COUNTER":51+ draftState.counter -= action.payload52+ break53+ }54+ })55+56+export const reduceCounterCurriedProducer = produce(57+ (draftState: Draft<State>, action: Action) => {58+ switch (action.type) {59+ case "ADD_TO_COUNTER":60+ draftState.counter += action.payload61+ break62+ case "SUB_FROM_COUNTER":63+ draftState.counter -= action.payload64+ break65+ }66+ },67+ initialState68+)69+70+/// =============== Reducers71+72+export const reduce = redux.combineReducers({73+ counterReducer: reduceCounterProducer74+})75+76+export const curredReduce = redux.combineReducers({77+ counterReducer: reduceCounterCurriedProducer78+})79+80+// reducing the current state to get the next state!81+// console.log(reduce(initialState, addToCounter(12));82+83+// ================ store84+85+export const store = redux.createStore(reduce)86+export const curriedStore = redux.createStore(curredReduce)87+88+it("#470 works with Redux combine reducers", () => {89+ assert(90+ store.getState().counterReducer,91+ _ as {92+ counter: number93+ }94+ )95+ assert(96+ curriedStore.getState().counterReducer,97+ _ as {98+ readonly counter: number99+ }100+ )101+})modified:docs/api.md+2 added
6 unmodified lines7891011121314151627 unmodified lines6 unmodified lines
| Exported name | Description | Section || --- | --- | --- || `applyPatches` | Given a base state or draft, and a set of patches, applies the patches | [Patches](patches.md) || `castDraft` | Converts any immutable type to its mutable counterpart. This is just a cast and doesn't actually do anything. | [TypeScript](typescript.md) || `castImmutable` | Converts any mutable type to its immutable counterpart. This is just a cast and doesn't actually do anything. | [TypeScript](typescript.md) || `createDraft` | Given a base state, creates a mutable draft for which any modifications will be recorded | [Async](async.md) || `Draft<T>` | Exposed TypeScript type to convert an immutable type to a mutable type | [TypeScript](typescript.md) || `finishDraft` | Given an draft created using `createDraft`, seals the draft and produces and returns the next immutable state that captures all the changes | [Async](async.md) || `Immer` | constructor that can be used to create a second "immer" instance (exposing all APIs listed in this instance), that doesn't share its settings with global instance. Can also be used to attach further hooks that are triggered during object finalization, such as `onAssign`, `onDelete` and `onCopy`. | [See source](https://github.com/immerjs/immer/blob/cb1c6dd8a33073aaa0a4d881c94ec7ab1c1be7f6/src/immer.d.ts#L224-L233) |27 unmodified linesmodified:docs/typescript.md+57 added
64 unmodified lines65 ```66 67 _Note: Since TypeScript support for recursive types is limited, and there is no co- contravariance, it might the easiest to not type your state as `readonly` (Immer will still protect against accidental mutations)_68 69+## Cast utilities70+71+The types inside and outside a `produce` can be conceptually the same, but from a practical perspective different. For example, the `State` in the examples above should be considered immutable outside `produce`, but mutable inside `produce`.72+73+Sometimes this leads to practical conflicts. Take the following example:74+75+```typescript76+type Todo = {readonly done: boolean}77+78+type State = {79+ readonly finishedTodos: readonly Todo[]80+ readonly unfinishedTodos: readonly Todo[]81+}82+83+function markAllFinished(state: State) {84+ produce(state, draft => {85+ draft.finishedTodos = state.unfinishedTodos86+ })87+}88+```89+90+This will generate the error:91+92+```93+The type 'readonly Todo[]' is 'readonly' and cannot be assigned to the mutable type '{ done: boolean; }[]'94+```95+96+The reason for this error is that we assing our read only, immutable array to our draft, which expects a mutable type, with methods like `.push` etc etc. As far as TS is concerned, those are not exposed from our original `State`. To hint TypeScript that we want to upcast the collection here to a mutable array for draft purposes, we can use the utility `asDraft`:97+98+`draft.finishedTodos = castDraft(state.unfinishedTodos)` will make the error disappear.99+100+There is also the utility `castImmutable`, in case you ever need to achieve the opposite. Note that these utilities are for all practical purposes no-ops, they will just return their original value.101+102+Tip: You can combine `castImmutable` with `produce` to type the return type of `produce` as something immutable, even when the original state was mutable:103+104+```typescript105+// a mutable data structure106+const baseState = {107+ todos: [{108+ done: false109+ }]110+}111+112+const nextState = castImmutable(produce(baseState, _draft => {}))113+114+// inferred type of nextState is now:115+{116+ readonly todos: ReadonlyArray<{117+ readonly done: boolean118+ }>119+})120+```121+122+## Compatibility123+124+**Note:** Immer v5.3+ supports TypeScript v3.7+ only.125+126 **Note:** Immer v1.9+ supports TypeScript v3.1+ only.127 128 **Note:** Immer v3.0+ supports TypeScript v3.4+ only.129 1 unmodified linemodified:src/common.ts+2 added-1 removed
37 unmodified lines38 return !proto || proto === Object.prototype39 }40 41 /** Get the underlying object that is represented by the given draft */42-export function original<T>(value: Drafted<T>): T | undefined {42+export function original<T>(value: T): T | undefined43+export function original(value: Drafted<any>): any {44 if (value && value[DRAFT_STATE]) {45 return value[DRAFT_STATE].base as any46 }47 // otherwise return undefined165 unmodified linesmodified:src/extends.ts+1 added
1234519 unmodified lines/* istanbul ignore next */var extendStatics = function(d: any, b: any): any { extendStatics = Object.setPrototypeOf || ({__proto__: []} instanceof Array &&19 unmodified linesmodified:src/index.ts+26 added-1 removed
1-import {IProduce, IProduceWithPatches, Immer} from "./internal"1+import {2+ IProduce,3+ IProduceWithPatches,4+ Immer,5+ Draft,6+ Immutable7+} from "./internal"8 9 export {10 Draft,11 Immutable,75 unmodified lines87 * changes that were made.88 */89 export const finishDraft = immer.finishDraft.bind(immer)90 91+/**92+ * This function is actually a no-op, but can be used to cast an immutable type93+ * to an draft type and make TypeScript happy94+ *95+ * @param value96+ */97+export function castDraft<T>(value: T): Draft<T> {98+ return value as any99+}100+101+/**102+ * This function is actually a no-op, but can be used to cast a mutable type103+ * to an immutable type and make TypeScript happy104+ * @param value105+ */106+export function castImmutable<T>(value: T): Immutable<T> {107+ return value as any108+}109+110 export {Immer}modified:src/internal.ts+2 added-1 removed
1 export * from "./env"2 export * from "./extends"3-export * from "./types"3+export * from "./types-external"4+export * from "./types-internal"5 export * from "./common"6 export * from "./scope"7 export * from "./finalize"8 export * from "./proxy"5 unmodified linesmodified:src/map.ts-3 removed
91 unmodified lines92 assertUnrevoked(state)93 prepareCopy(state)94 state.scope.immer.markChanged(state)95 state.assigned = new Map()96- for (const key of latest(state).keys()) {97- state.assigned.set(key, false)98- }96 return state.copy!.clear()97 }98 99 p.forEach = function(85 unmodified linesadded:src/types-external.ts+165 added
1+import {Nothing} from "./internal"2+3+type Tail<T extends any[]> = ((...t: T) => any) extends (4+ _: any,5+ ...tail: infer TT6+) => any7+ ? TT8+ : []9+10+/** Object types that should never be mapped */11+type AtomicObject =12+ | Function13+ | Promise<any>14+ | Date15+ | RegExp16+ | Boolean17+ | Number18+ | String19+20+/**21+ * These should also never be mapped but must be tested after regular Map and22+ * Set23+ */24+type WeakReferences = WeakMap<any, any> | WeakSet<any>25+26+export type Draft<T> = T extends AtomicObject27+ ? T28+ : T extends ReadonlyMap<infer K, infer V> // Map extends ReadonlyMap29+ ? Map<Draft<K>, Draft<V>>30+ : T extends ReadonlySet<infer V> // Set extends ReadonlySet31+ ? Set<Draft<V>>32+ : T extends WeakReferences33+ ? T34+ : T extends object35+ ? {-readonly [K in keyof T]: Draft<T[K]>}36+ : T37+38+/** Convert a mutable type into a readonly type */39+export type Immutable<T> = T extends AtomicObject40+ ? T41+ : T extends ReadonlyMap<infer K, infer V> // Map extends ReadonlyMap42+ ? ReadonlyMap<Immutable<K>, Immutable<V>>43+ : T extends ReadonlySet<infer V> // Set extends ReadonlySet44+ ? ReadonlySet<Immutable<V>>45+ : T extends WeakReferences46+ ? T47+ : T extends object48+ ? {readonly [K in keyof T]: Immutable<T[K]>}49+ : T50+51+export interface Patch {52+ op: "replace" | "remove" | "add"53+ path: (string | number)[]54+ value?: any55+}56+57+export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void58+59+/** Converts `nothing` into `undefined` */60+type FromNothing<T> = T extends Nothing ? undefined : T61+62+/** The inferred return type of `produce` */63+export type Produced<Base, Return> = Return extends void64+ ? Base65+ : Return extends Promise<infer Result>66+ ? Promise<Result extends void ? Base : FromNothing<Result>>67+ : FromNothing<Return>68+69+/**70+ * The `produce` function takes a value and a "recipe function" (whose71+ * return value often depends on the base state). The recipe function is72+ * free to mutate its first argument however it wants. All mutations are73+ * only ever applied to a __copy__ of the base state.74+ *75+ * Pass only a function to create a "curried producer" which relieves you76+ * from passing the recipe function every time.77+ *78+ * Only plain objects and arrays are made mutable. All other objects are79+ * considered uncopyable.80+ *81+ * Note: This function is __bound__ to its `Immer` instance.82+ *83+ * @param {any} base - the initial state84+ * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified85+ * @param {Function} patchListener - optional function that will be called with all the patches produced here86+ * @returns {any} a new state, or the initial state if nothing was modified87+ */88+export interface IProduce {89+ /** Curried producer */90+ <91+ Recipe extends (...args: any[]) => any,92+ Params extends any[] = Parameters<Recipe>,93+ T = Params[0]94+ >(95+ recipe: Recipe96+ ): <Base extends Immutable<T>>(97+ base: Base,98+ ...rest: Tail<Params>99+ ) => Produced<Base, ReturnType<Recipe>>100+ // ^ by making the returned type generic, the actual type of the passed in object is preferred101+ // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe102+ // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!103+104+ /** Curried producer with initial state */105+ <106+ Recipe extends (...args: any[]) => any,107+ Params extends any[] = Parameters<Recipe>,108+ T = Params[0]109+ >(110+ recipe: Recipe,111+ initialState: Immutable<T>112+ ): <Base extends Immutable<T>>(113+ base?: Base,114+ ...rest: Tail<Params>115+ ) => Produced<Base, ReturnType<Recipe>>116+117+ /** Normal producer */118+ <Base, D = Draft<Base>, Return = void>(119+ base: Base,120+ recipe: (draft: D) => Return,121+ listener?: PatchListener122+ ): Produced<Base, Return>123+}124+125+/**126+ * Like `produce`, but instead of just returning the new state,127+ * a tuple is returned with [nextState, patches, inversePatches]128+ *129+ * Like produce, this function supports currying130+ */131+export interface IProduceWithPatches {132+ /** Curried producer */133+ <134+ Recipe extends (...args: any[]) => any,135+ Params extends any[] = Parameters<Recipe>,136+ T = Params[0]137+ >(138+ recipe: Recipe139+ ): <Base extends Immutable<T>>(140+ base: Base,141+ ...rest: Tail<Params>142+ ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]143+ // ^ by making the returned type generic, the actual type of the passed in object is preferred144+ // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe145+ // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!146+147+ /** Curried producer with initial state */148+ <149+ Recipe extends (...args: any[]) => any,150+ Params extends any[] = Parameters<Recipe>,151+ T = Params[0]152+ >(153+ recipe: Recipe,154+ initialState: Immutable<T>155+ ): <Base extends Immutable<T>>(156+ base?: Base,157+ ...rest: Tail<Params>158+ ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]159+160+ /** Normal producer */161+ <Base, D = Draft<Base>, Return = void>(162+ base: Base,163+ recipe: (draft: D) => Return164+ ): [Produced<Base, Return>, Patch[], Patch[]]165+}added:src/types-internal.ts+54 added
1+import {2+ SetState,3+ ImmerScope,4+ ProxyObjectState,5+ ProxyArrayState,6+ ES5ObjectState,7+ ES5ArrayState,8+ MapState,9+ DRAFT_STATE10+} from "./internal"11+12+export type Objectish = AnyObject | AnyArray | AnyMap | AnySet13+export type ObjectishNoSet = AnyObject | AnyArray | AnyMap14+15+export type AnyObject = {[key: string]: any}16+export type AnyArray = Array<any>17+export type AnySet = Set<any>18+export type AnyMap = Map<any, any>19+export enum Archtype {20+ Object,21+ Array,22+ Map,23+ Set24+}25+26+export enum ProxyType {27+ ProxyObject,28+ ProxyArray,29+ ES5Object,30+ ES5Array,31+ Map,32+ Set33+}34+35+export interface ImmerBaseState {36+ parent?: ImmerState37+ scope: ImmerScope38+ modified: boolean39+ finalized: boolean40+ isManual: boolean41+}42+43+export type ImmerState =44+ | ProxyObjectState45+ | ProxyArrayState46+ | ES5ObjectState47+ | ES5ArrayState48+ | MapState49+ | SetState50+51+// The _internal_ type used for drafts (not to be confused with Draft, which is public facing)52+export type Drafted<Base = any, T extends ImmerState = ImmerState> = {53+ [DRAFT_STATE]: T54+} & Basedeleted:src/types.ts-221 removed
1-import {2- SetState,3- ImmerScope,4- ProxyObjectState,5- ProxyArrayState,6- ES5ObjectState,7- ES5ArrayState,8- MapState,9- DRAFT_STATE,10- Nothing11-} from "./internal"12-13-export type Objectish = AnyObject | AnyArray | AnyMap | AnySet14-export type ObjectishNoSet = AnyObject | AnyArray | AnyMap15-16-export type AnyObject = {[key: string]: any}17-export type AnyArray = Array<any>18-export type AnySet = Set<any>19-export type AnyMap = Map<any, any>20-export enum Archtype {21- Object,22- Array,23- Map,24- Set25-}26-27-export enum ProxyType {28- ProxyObject,29- ProxyArray,30- ES5Object,31- ES5Array,32- Map,33- Set34-}35-36-export interface ImmerBaseState {37- parent?: ImmerState38- scope: ImmerScope39- modified: boolean40- finalized: boolean41- isManual: boolean42-}43-44-export type ImmerState =45- | ProxyObjectState46- | ProxyArrayState47- | ES5ObjectState48- | ES5ArrayState49- | MapState50- | SetState51-52-// The _internal_ type used for drafts (not to be confused with Draft, which is public facing)53-export type Drafted<Base = any, T extends ImmerState = ImmerState> = {54- [DRAFT_STATE]: T55-} & Base56-57-type Tail<T extends any[]> = ((...t: T) => any) extends (58- _: any,59- ...tail: infer TT60-) => any61- ? TT62- : []63-64-/** Object types that should never be mapped */65-type AtomicObject =66- | Function67- | WeakMap<any, any>68- | WeakSet<any>69- | Promise<any>70- | Date71- | RegExp72- | Boolean73- | Number74- | String75-76-export type Draft<T> = T extends AtomicObject77- ? T78- : T extends Map<infer K, infer V>79- ? DraftMap<K, V>80- : T extends Set<infer V>81- ? DraftSet<V>82- : T extends object83- ? {-readonly [K in keyof T]: Draft<T[K]>}84- : T85-86-// Inline these in ts 3.787-interface DraftMap<K, V> extends Map<Draft<K>, Draft<V>> {}88-89-// Inline these in ts 3.790-interface DraftSet<V> extends Set<Draft<V>> {}91-92-/** Convert a mutable type into a readonly type */93-export type Immutable<T> = T extends AtomicObject94- ? T95- : T extends Map<infer K, infer V> // Ideally, but wait for TS 3.7: ? Omit<ImmutableMap<K, V>, "set" | "delete" | "clear">96- ? ImmutableMap<K, V>97- : T extends Set<infer V> // Ideally, but wait for TS 3.7: ? Omit<ImmutableSet<V>, "add" | "delete" | "clear">98- ? ImmutableSet<V>99- : T extends object100- ? {readonly [K in keyof T]: Immutable<T[K]>}101- : T102-103-interface ImmutableMap<K, V> extends Map<Immutable<K>, Immutable<V>> {}104-105-interface ImmutableSet<V> extends Set<Immutable<V>> {}106-107-export interface Patch {108- op: "replace" | "remove" | "add"109- path: (string | number)[]110- value?: any111-}112-113-export type PatchListener = (patches: Patch[], inversePatches: Patch[]) => void114-115-/** Converts `nothing` into `undefined` */116-type FromNothing<T> = T extends Nothing ? undefined : T117-118-/** The inferred return type of `produce` */119-export type Produced<Base, Return> = Return extends void120- ? Base121- : Return extends Promise<infer Result>122- ? Promise<Result extends void ? Base : FromNothing<Result>>123- : FromNothing<Return>124-125-/**126- * The `produce` function takes a value and a "recipe function" (whose127- * return value often depends on the base state). The recipe function is128- * free to mutate its first argument however it wants. All mutations are129- * only ever applied to a __copy__ of the base state.130- *131- * Pass only a function to create a "curried producer" which relieves you132- * from passing the recipe function every time.133- *134- * Only plain objects and arrays are made mutable. All other objects are135- * considered uncopyable.136- *137- * Note: This function is __bound__ to its `Immer` instance.138- *139- * @param {any} base - the initial state140- * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified141- * @param {Function} patchListener - optional function that will be called with all the patches produced here142- * @returns {any} a new state, or the initial state if nothing was modified143- */144-export interface IProduce {145- /** Curried producer */146- <147- Recipe extends (...args: any[]) => any,148- Params extends any[] = Parameters<Recipe>,149- T = Params[0]150- >(151- recipe: Recipe152- ): <Base extends Immutable<T>>(153- base: Base,154- ...rest: Tail<Params>155- ) => Produced<Base, ReturnType<Recipe>>156- // ^ by making the returned type generic, the actual type of the passed in object is preferred157- // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe158- // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!159-160- /** Curried producer with initial state */161- <162- Recipe extends (...args: any[]) => any,163- Params extends any[] = Parameters<Recipe>,164- T = Params[0]165- >(166- recipe: Recipe,167- initialState: Immutable<T>168- ): <Base extends Immutable<T>>(169- base?: Base,170- ...rest: Tail<Params>171- ) => Produced<Base, ReturnType<Recipe>>172-173- /** Normal producer */174- <Base, D = Draft<Base>, Return = void>(175- base: Base,176- recipe: (draft: D) => Return,177- listener?: PatchListener178- ): Produced<Base, Return>179-}180-181-/**182- * Like `produce`, but instead of just returning the new state,183- * a tuple is returned with [nextState, patches, inversePatches]184- *185- * Like produce, this function supports currying186- */187-export interface IProduceWithPatches {188- /** Curried producer */189- <190- Recipe extends (...args: any[]) => any,191- Params extends any[] = Parameters<Recipe>,192- T = Params[0]193- >(194- recipe: Recipe195- ): <Base extends Immutable<T>>(196- base: Base,197- ...rest: Tail<Params>198- ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]199- // ^ by making the returned type generic, the actual type of the passed in object is preferred200- // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe201- // Note: the type of S is the widened version of T, so it can have more props than T, but that is technically actually correct!202-203- /** Curried producer with initial state */204- <205- Recipe extends (...args: any[]) => any,206- Params extends any[] = Parameters<Recipe>,207- T = Params[0]208- >(209- recipe: Recipe,210- initialState: Immutable<T>211- ): <Base extends Immutable<T>>(212- base?: Base,213- ...rest: Tail<Params>214- ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]215-216- /** Normal producer */217- <Base, D = Draft<Base>, Return = void>(218- base: Base,219- recipe: (draft: D) => Return220- ): [Produced<Base, Return>, Patch[], Patch[]]221-}modified:package.json+2 added
13 unmodified lines14 "test": "jest",15 "test:perf": "NODE_ENV=production yarn-or-npm build && cd __performance_tests__ && babel-node add-data.js && babel-node todo.js && babel-node incremental.js",16 "test:flow": "yarn-or-npm flow check __tests__/flow",17 "watch": "jest --watch",18+ "coverage": "jest --coverage",19 "coveralls": "jest --coverage && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf ./coverage",20 "build": "rimraf dist/ && yarn-or-npm bili && yarn-or-npm typed",21 "typed": "cpx 'src/immer.js.flow' dist -v",22 "publish-docs": "cd website && GIT_USER=mweststrate USE_SSH=true yarn run publish-gh-pages",49 unmodified lines72 "lodash": "^4.17.4",73 "lodash.clonedeep": "^4.5.0",74 "prettier": "1.19.1",75 "pretty-quick": "^1.8.0",76+ "redux": "^4.0.5",77 "regenerator-runtime": "^0.11.1",78 "rimraf": "^2.6.2",79 "rollup-plugin-typescript2": "^0.25.3",80 "seamless-immutable": "^7.1.3",25 unmodified linesmodified:yarn.lock+14 added-1 removed
4709 unmodified lines4710 integrity sha512-VeIAFslyIerEJLXHziedo2basKbMKtTw3vfn5IzG0XTjhAVEJyNHnL2p7vc+wBDSdQuUpNw3M2u6xb9QsAY5Eg==4711 dependencies:4712 chalk "^2.0.1"4713 4714-loose-envify@^1.0.0:4714+loose-envify@^1.0.0, loose-envify@^1.4.0:4715 version "1.4.0"4716 resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf"4717 integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==4718 dependencies:1323 unmodified lines6042 integrity sha512-wlgPA6cCIIg9gKz0fgAPjnzh4yR/LnXovwuo9hvyGvx3h8nX4+/iLZplfUWasXpqD8BdnGnP5njOFjkUwPzvjA==6043 dependencies:6044 util.promisify "^1.0.0"6045 6046+redux@^4.0.5:6047+ version "4.0.5"6048+ resolved "https://registry.yarnpkg.com/redux/-/redux-4.0.5.tgz#4db5de5816e17891de8a80c424232d06f051d93f"6049+ integrity sha512-VSz1uMAH24DM6MF72vcojpYPtrTUu3ByVWfPL1nPfVRb5mZVTve5GnNCUV53QM/BZ66xfWrm0CTWoM+Xlz8V1w==6050+ dependencies:6051+ loose-envify "^1.4.0"6052+ symbol-observable "^1.2.0"6053+6054 regenerate-unicode-properties@^8.0.2:6055 version "8.0.2"6056 resolved "https://registry.yarnpkg.com/regenerate-unicode-properties/-/regenerate-unicode-properties-8.0.2.tgz#7b38faa296252376d363558cfbda90c9ce709662"6057 integrity sha512-SbA/iNrBUf6Pv2zU8Ekv1Qbhv92yxL4hiDa2siuxs4KKn4oOoMDHXjAf7+Nz9qinUQ46B1LcWEi/PhJfPWpZWQ==848 unmodified lines6906 stable "^0.1.8"6907 unquote "~1.1.1"6908 util.promisify "~1.0.0"6909 6910+symbol-observable@^1.2.0:6911+ version "1.2.0"6912+ resolved "https://registry.yarnpkg.com/symbol-observable/-/symbol-observable-1.2.0.tgz#c22688aed4eab3cdc2dfeacbb561660560a00804"6913+ integrity sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ==6914+6915 symbol-tree@^3.2.2:6916 version "3.2.2"6917 resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.2.tgz#ae27db38f660a7ae2e1c3b7d1bc290819b8519e6"6918 integrity sha1-rifbOPZgp64uHDt9G8KQgZuFGeY=467 unmodified lines