Skip to content
Myr

feature: Improved typescript types

Before adoption: this commit came in with the history the project adopted, so no landing records it.

The TypeScript typings of Immer have been rewritten, and support better inference now and are more accurate. The best practices are documented here: https://immerjs.github.io/immer/typescript. Please visit that page first when running into any compile errors after updating. The following changes have been made: Immer can now infer the type of the `draft` for curried producers, if they are directly passed to another function / context from which the type can be inferred. So lines like these will now be strongly typed: `setTodo(produce(draft => { draft.done = true }))`, where `setTodo` is a React state updater (for example). Fixes #720. Immer will now better respect the original types passed to a producer, and generally not wrap any returned types with `Immutable` automatically. BREAKING CHANGE: It is no longer allowed to return `nothing` from a recipe if the target state doesn't accept `undefined`. BREAKING CHANGE: It is no longer allowed to return arbitrary things from a recipe. Recipes should either return nothing, or something that is assignable to the original state type. This will catch mistakes with accidental returns earlier.

authored by Michel Weststrate · committed by GitHub · parent b7fcf7f · Browse files · 7 files+759 added−229 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+759 added−229 removed

  • tests:+532 added−131 removed
  • other:+227 added−98 removed

7 files+759 added−229 removed

modified:__tests__/produce.ts+324 added-56 removed
46 unmodified lines
47 arr2: [{value: "foo"}, {value: "asf"}]48}4950it("can update readonly state via standard api", () => {51 const newState = produce<State>(state, draft => {51 const newState = produce(state, draft => {52 draft.num++53 draft.foo = "bar"54 draft.bar = "foo"55 draft.baz.x++
2 unmodified lines
58 draft.arr.push({value: "asf"})59 draft.arr2[0].value = "foo"60 draft.arr2.push({value: "asf"})61 })62 assert(newState, state)62 assert(newState, _ as State)63})6465// NOTE: only when the function type is inferred66it("can infer state type from default state", () => {67 type State = {readonly a: number}68 type Recipe = <S extends State>(state?: S | undefined) => S68 type Recipe = (state?: State | undefined) => State6970 let foo = produce((_: any) => {}, _ as State)71 assert(foo, _ as Recipe)72})7374it("can infer state type from recipe function", () => {75 type State = {readonly a: string} | {readonly b: string}76 type Recipe = <S extends State>(state: S) => S75 type A = {readonly a: string}76 type B = {readonly b: string}77 type State = A | B78 type Recipe = (state: State) => State7978 let foo = produce((_: Draft<State>) => {})80 let foo = produce((draft: State) => {81 assert(draft, _ as State)82 if (Math.random() > 0.5) return {a: "test"}83 else return {b: "boe"}84 })85 const x = foo({a: ""})86 const y = foo({b: ""})87 assert(foo, _ as Recipe)88})8990it("can infer state type from recipe function with arguments", () => {91 type State = {readonly a: string} | {readonly b: string}84 type Recipe = <S extends State>(state: S, x: number) => S92 type Recipe = (state: State, x: number) => State9386 let foo = produce((draft: Draft<State>, x: number) => {})94 let foo = produce<State, [number]>((draft, x) => {95 assert(draft, _ as Draft<State>)96 assert(x, _ as number)97 })98 assert(foo, _ as Recipe)99})100101it("can infer state type from recipe function with arguments and initial state", () => {102 type State = {readonly a: string} | {readonly b: string}92 type Recipe = <S extends State>(state: S | undefined, x: number) => S103 type Recipe = (state: State | undefined, x: number) => State104105 let foo = produce((draft: Draft<State>, x: number) => {}, _ as State)106 assert(foo, _ as Recipe)107})
57 unmodified lines
165 type State = {readonly a: 1}166167 // No initial state:168 {158 type Recipe = <S extends State>(state: S, a: number, b: number) => S169 type Recipe = (state: State, a: number, b: number) => State170 let foo = produce((s: State, a: number, b: number) => {})171 assert(foo, _ as Recipe)172 foo(_ as State, 1, 2)173 }174175 // Using argument parameters:176 {166 type Recipe = <S extends State>(state: S, ...rest: number[]) => S177 type Recipe = (state: Immutable<State>, ...rest: number[]) => Draft<State>178 let woo = produce((state: Draft<State>, ...args: number[]) => {})179 assert(woo, _ as Recipe)180 woo(_ as State, 1, 2)181 }182183 // With initial state:184 {174 type Recipe = <S extends State>(175 state?: S | undefined,176 ...rest: number[]177 ) => S185 type Recipe = (state?: State | undefined, ...rest: number[]) => State186 let bar = produce((state: Draft<State>, ...args: number[]) => {},187 _ as State)188 assert(bar, _ as Recipe)189 bar(_ as State, 1, 2)
2 unmodified lines
192 }193194 // When args is a tuple:195 {188 type Recipe = <S extends State>(189 state: S | undefined,196 type Recipe = (197 state: State | undefined,198 first: string,199 ...rest: number[]192 ) => S200 ) => State201 let tup = produce(202 (state: Draft<State>, ...args: [string, ...number[]]) => {},203 _ as State204 )
6 unmodified lines
211 it("can be passed a readonly array", () => {212 // No initial state:213 {214 let foo = produce((state: string[]) => {})207 assert(foo, _ as <S extends readonly string[]>(state: S) => S)215 assert(foo, _ as (state: readonly string[]) => string[])216 foo([] as ReadonlyArray<string>)217 }218219 // With initial state:220 {221 let bar = produce(() => {}, [] as ReadonlyArray<string>)222 assert(223 bar,216 _ as <S extends readonly string[]>(state?: S | undefined) => S224 _ as (state?: readonly string[] | undefined) => readonly string[]225 )226 bar([] as ReadonlyArray<string>)227 bar(undefined)228 bar()
1 unmodified line
230 })231})232233it("works with return type of: number", () => {226 let base = _ as {a: number}227 let result = produce(base, () => 1)228 assert(result, _ as number)229})230231it("works with return type of: number | undefined", () => {234 let base = {a: 0} as {a: number}233 let result = produce(base, draft => {234 return draft.a < 0 ? 0 : undefined235 })236 assert(result, _ as {a: number} | number)235 {236 if (Math.random() === 100) {237 // @ts-expect-error, this return accidentally a number, this is probably a dev error!238 let result = produce(base, draft => draft.a++)239 }240 }241 {242 let result = produce(base, draft => void draft.a++)243 assert(result, _ as {a: number})244 }245})246247it("can return an object type that is identical to the base type", () => {248 let base = {a: 0} as {a: number}249 let result = produce(base, draft => {250 return draft.a < 0 ? {a: 0} : undefined251 })244 // TODO: Can we resolve the weird union of identical object types?245 assert(result, _ as {a: number} | {a: number})252 assert(result, _ as {a: number})253})254248it("can return an object type that is _not_ assignable to the base type", () => {255it("can NOT return an object type that is _not_ assignable to the base type", () => {256 let base = {a: 0} as {a: number}257 // @ts-expect-error258 let result = produce(base, draft => {259 return draft.a < 0 ? {a: true} : undefined260 })253 assert(result, _ as {a: number} | {a: boolean})261})262263it("does not enforce immutability at the type level", () => {264 let result = produce([] as any[], draft => {
2 unmodified lines
267 assert(result, _ as any[])268})269270it("can produce an undefined value", () => {264 let base = {a: 0} as {readonly a: number}271 type State = {readonly a: number} | undefined272 const base = {a: 0} as State273274 // Return only nothing.275 let result = produce(base, _ => nothing)268 assert(result, undefined)276 assert(result, _ as State)277278 // Return maybe nothing.279 let result2 = produce(base, draft => {272 if (draft.a > 0) return nothing280 if (draft?.a ?? 0 > 0) return nothing281 })274 assert(result2, _ as typeof base | undefined)282 assert(result2, _ as State)283})284285it("can return the draft itself", () => {286 let base = _ as {readonly a: number}287 let result = produce(base, draft => draft)288281 // Currently, the `readonly` modifier is lost.282 assert(result, _ as {a: number})289 assert(result, _ as {readonly a: number})290})291292it("can return a promise", () => {293 type Base = {readonly a: number}294 let base = {a: 0} as Base295296 // Return a promise only.297 let res1 = produce(base, draft => {291 return Promise.resolve(draft.a > 0 ? null : undefined)298 return Promise.resolve(draft)299 })293 assert(res1, _ as Promise<Base | null>)300 assert(res1, _ as Promise<Base>)301302 // Return a promise or undefined.303 let res2 = produce(base, draft => {297 if (draft.a > 0) return Promise.resolve()304 return Promise.resolve()305 })299 assert(res2, _ as Base | Promise<Base>)306 assert(res2, _ as Promise<Base>)307})308309it("works with `void` hack", () => {310 let base = {a: 0} as {readonly a: number}
26 unmodified lines
337 ]338 }339 type State = typeof state340334 const newState: State = produce(state, draft => {341 const newState = produce(state, draft => {342 draft.price += 5343 draft.todos.push({344 title: "hi",345 done: true346 })347 })348 assert(newState, _ as State)349350 const reducer = (draft: State) => {351 draft.price += 5352 draft.todos.push({
6 unmodified lines
359 const newState4 = produce(reducer, state)(state)360 assert(newState4, _ as State)361 // no argument case, in that case, immutable version recipe first arg will be inferred362 const newState5 = produce(reducer, state)()355 assert(newState5, _ as Immutable<State>)356 // we can force the return type of the reducer by passing the generic argument357 const newState3 = produce(reducer, state)<State>()363 assert(newState5, _ as State)364 // we can force the return type of the reducer by casting the initial state365 const newState3 = produce(reducer, state as State)()366 assert(newState3, _ as State)367})368369it("can work with readonly base types", () => {
14 unmodified lines
384 }385 ]386 }387380 const newState: State = produce(state, draft => {388 const newState = produce(state, draft => {389 draft.price + 5390 draft.todos.push({391 title: "hi",392 done: true393 })394 })395 assert(newState, _ as State)396 assert(newState, _ as Immutable<State>) // cause that is the same!397398 const reducer = (draft: Draft<State>) => {399 draft.price += 5400 draft.todos.push({
8 unmodified lines
409 const newState4 = produce(reducer, state)(state)410 assert(newState4, _ as State)411 // no argument case, in that case, immutable version recipe first arg will be inferred412 const newState5 = produce(reducer, state)()403 assert(newState5, _ as Immutable<State>)404 // we can force the return type of the reducer by passing the generic argument405 const newState3 = produce(reducer, state)<State>()413 assert(newState5, _ as State)414 // we can force the return type of the reducer by casting initial argument415 const newState3 = produce(reducer, state as State)()416 assert(newState3, _ as State)417})418419it("works with generic array", () => {
27 unmodified lines
447})448449it("works with readonly Map and Set", () => {450 type S = {readonly x: number}441 const m = new Map<string, S>([["a", {x: 1}]])442 const s = new Set<S>([{x: 2}])451 const m: ReadonlyMap<string, S> = new Map([["a", {x: 1}]])452 const s: ReadonlySet<S> = new Set([{x: 2}])453454 const res1 = produce(m, (draft: Draft<Map<string, S>>) => {455 assert(draft, _ as Map<string, {x: number}>)456 })447 assert(res1, _ as Map<string, {readonly x: number}>)457 assert(res1, _ as ReadonlyMap<string, {readonly x: number}>)458459 const res2 = produce(s, (draft: Draft<Set<S>>) => {460 assert(draft, _ as Set<{x: number}>)461 })452 assert(res2, _ as Set<{readonly x: number}>)462 assert(res2, _ as ReadonlySet<{readonly x: number}>)463})464465it("works with ReadonlyMap and ReadonlySet", () => {466 type S = {readonly x: number}
36 unmodified lines
503 expect(z.x).toBe(4)504 // @ts-expect-error505 expect(z.z).toBeUndefined()506})507508it("infers draft, #720", () => {509 function nextNumberCalculator(fn: (base: number) => number) {510 // noop511 }512513 const res2 = nextNumberCalculator(514 produce(draft => {515 // @ts-expect-error516 let x: string = draft517 return draft + 1518 })519 )520521 const res = nextNumberCalculator(522 produce(draft => {523 // @ts-expect-error524 let x: string = draft525 // return draft + 1;526 return undefined527 })528 )529})530531it("infers draft, #720 - 2", () => {532 function useState<S>(533 initialState: S | (() => S)534 ): [S, Dispatch<SetStateAction<S>>] {535 return [initialState, function() {}] as any536 }537 type Dispatch<A> = (value: A) => void538 type SetStateAction<S> = S | ((prevState: S) => S)539540 const [n, setN] = useState({x: 3})541542 setN(543 produce(draft => {544 // @ts-expect-error545 draft.y = 4546 draft.x = 5547 return draft548 })549 )550551 setN(552 produce(draft => {553 // @ts-expect-error554 draft.y = 4555 draft.x = 5556 // return draft + 1;557 return undefined558 })559 )560561 setN(562 produce(draft => {563 return {y: 3} as const564 })565 )566})567568it("infers draft, #720 - 3", () => {569 function useState<S>(570 initialState: S | (() => S)571 ): [S, Dispatch<SetStateAction<S>>] {572 return [initialState, function() {}] as any573 }574 type Dispatch<A> = (value: A) => void575 type SetStateAction<S> = S | ((prevState: S) => S)576577 const [n, setN] = useState({x: 3} as {readonly x: number})578579 setN(580 produce(draft => {581 // @ts-expect-error582 draft.y = 4583 draft.x = 5584 return draft585 })586 )587588 setN(589 produce(draft => {590 // @ts-expect-error591 draft.y = 4592 draft.x = 5593 // return draft + 1;594 return undefined595 })596 )597598 setN(599 produce(draft => {600 return {y: 3} as const601 })602 )603})604605it("infers curried", () => {606 type Todo = {title: string}607 {608 const fn = produce((draft: Todo) => {609 let x: string = draft.title610 })611612 fn({title: "test"})613 // @ts-expect-error614 fn(3)615 }616 {617 const fn = produce((draft: Todo) => {618 let x: string = draft.title619 return draft620 })621622 fn({title: "test"})623 // @ts-expect-error624 fn(3)625 }626})627628it("infers async curried", async () => {629 type Todo = {title: string}630 {631 const fn = produce(async (draft: Todo) => {632 let x: string = draft.title633 })634635 const res = await fn({title: "test"})636 // @ts-expect-error637 fn(3)638 assert(res, _ as Todo)639 }640 {641 const fn = produce(async (draft: Todo) => {642 let x: string = draft.title643 return draft644 })645646 const res = await fn({title: "test"})647 // @ts-expect-error648 fn(3)649 assert(res, _ as Todo)650 }651})652653{654 type State = {count: number}655 type ROState = Immutable<State>656 const base: any = {count: 0}657 {658 // basic659 const res = produce(base as State, draft => {660 draft.count++661 })662 assert(res, _ as State)663 }664 {665 // basic666 const res = produce<State>(base, draft => {667 draft.count++668 })669 assert(res, _ as State)670 }671 {672 // basic673 const res = produce(base as ROState, draft => {674 draft.count++675 })676 assert(res, _ as ROState)677 }678 {679 // curried680 const f = produce((state: State) => {681 state.count++682 })683 assert(f, _ as (state: Immutable<State>) => State)684 }685 {686 // curried687 const f = produce((state: Draft<ROState>) => {688 state.count++689 })690 assert(f, _ as (state: ROState) => State)691 }692 {693 // curried694 const f: (value: State) => State = produce(state => {695 state.count++696 })697 }698 {699 // curried700 const f: (value: ROState) => ROState = produce(state => {701 state.count++702 })703 }704 {705 // curried initial706 const f = produce(state => {707 state.count++708 }, _ as State)709 assert(f, _ as (state?: State) => State)710 }711 {712 // curried initial713 const f = produce(state => {714 state.count++715 }, _ as ROState)716 assert(f, _ as (state?: ROState) => ROState)717 }718 {719 // curried720 const f: (value: State) => State = produce(state => {721 state.count++722 }, base as ROState)723 }724 {725 // curried726 const f: (value: ROState) => ROState = produce(state => {727 state.count++728 }, base as ROState)729 }730 {731 // nothing allowed732 const res = produce(base as State | undefined, draft => {733 return nothing734 })735 assert(res, _ as State | undefined)736 }737 {738 // nothing not allowed739 // @ts-expect-error740 produce(base as State, draft => {741 return nothing742 })743 }744 {745 const f = produce((draft: State) => {})746 const n = f(base as State)747 assert(n, _ as State)748 }749 {750 const f = produce((draft: Draft<ROState>) => {751 draft.count++752 })753 const n = f(base as ROState)754 assert(n, _ as State)755 }756 {757 // explictly use generic758 const f = produce<ROState>(draft => {759 draft.count++760 })761 const n = f(base as ROState)762 assert(n, _ as ROState) // yay!763 }764}
modified:__tests__/redux.ts+208 added-75 removed
modified:src/types/types-external.ts+134 added-65 removed
1import {Nothing} from "../internal"23type Tail<T extends any[]> = ((...t: T) => any) extends (4 _: any,5 ...tail: infer TT6) => any7 ? TT8 : []3type AnyFunc = (...args: any[]) => any45type PrimitiveType = number | string | boolean67/** Object types that should never be mapped */
71 unmodified lines
79 ? Promise<Result extends void ? Base : FromNothing<Result>>80 : FromNothing<Return>8182/**83 * Utility types84 */85type PatchesTuple<T> = readonly [T, Patch[], Patch[]]8687type ValidRecipeReturnType<State> =88 | State89 | void90 | undefined91 | (State extends undefined ? Nothing : never)9293type ValidRecipeReturnTypePossiblyPromise<State> =94 | ValidRecipeReturnType<State>95 | Promise<ValidRecipeReturnType<State>>9697type PromisifyReturnIfNeeded<98 State,99 Recipe extends AnyFunc,100 UsePatches extends boolean101> = ReturnType<Recipe> extends Promise<any>102 ? Promise<UsePatches extends true ? PatchesTuple<State> : State>103 : UsePatches extends true104 ? PatchesTuple<State>105 : State106107/**108 * Core Producer inference109 */110type InferRecipeFromCurried<Curried> = Curried extends (111 base: infer State,112 ...rest: infer Args113) => any // extra assertion to make sure this is a proper curried function (state, args) => state114 ? ReturnType<Curried> extends State115 ? (116 draft: Draft<State>,117 ...rest: Args118 ) => ValidRecipeReturnType<Draft<State>>119 : never120 : never121122type InferInitialStateFromCurried<Curried> = Curried extends (123 base: infer State,124 ...rest: any[]125) => any // extra assertion to make sure this is a proper curried function (state, args) => state126 ? State127 : never128129type InferCurriedFromRecipe<130 Recipe,131 UsePatches extends boolean132> = Recipe extends (draft: infer DraftState, ...args: infer RestArgs) => any // verify return type133 ? ReturnType<Recipe> extends ValidRecipeReturnTypePossiblyPromise<DraftState>134 ? (135 base: Immutable<DraftState>,136 ...args: RestArgs137 ) => PromisifyReturnIfNeeded<DraftState, Recipe, UsePatches> // N.b. we return mutable draftstate, in case the recipe's first arg isn't read only, and that isn't expected as output either138 : never // incorrect return type139 : never // not a function140141type InferCurriedFromInitialStateAndRecipe<142 State,143 Recipe,144 UsePatches extends boolean145> = Recipe extends (146 draft: Draft<State>,147 ...rest: infer RestArgs148) => ValidRecipeReturnTypePossiblyPromise<State>149 ? (150 base?: State | undefined,151 ...args: RestArgs152 ) => PromisifyReturnIfNeeded<State, Recipe, UsePatches>153 : never // recipe doesn't match initial state154155/**156 * The `produce` function takes a value and a "recipe function" (whose157 * return value often depends on the base state). The recipe function is158 * free to mutate its first argument however it wants. All mutations are159 * only ever applied to a __copy__ of the base state.
11 unmodified lines
171 * @param {Function} patchListener - optional function that will be called with all the patches produced here172 * @returns {any} a new state, or the initial state if nothing was modified173 */174export interface IProduce {107 /** Curried producer */108 <109 Recipe extends (...args: any[]) => any,110 Params extends any[] = Parameters<Recipe>,111 T = Params[0]112 >(113 recipe: Recipe114 ): <Base extends Immutable<T>>(115 base: Base,116 ...rest: Tail<Params>117 ) => Produced<Base, ReturnType<Recipe>>118 // ^ by making the returned type generic, the actual type of the passed in object is preferred119 // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe120 // 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!175 /** Curried producer that infers the recipe from the curried output function (e.g. when passing to setState) */176 <Curried>(177 recipe: InferRecipeFromCurried<Curried>,178 initialState?: InferInitialStateFromCurried<Curried>179 ): Curried180122 /** Curried producer with initial state */123 <124 Recipe extends (...args: any[]) => any,125 Params extends any[] = Parameters<Recipe>,126 T = Params[0]127 >(181 /** Curried producer that infers curried from the recipe */182 <Recipe extends AnyFunc>(recipe: Recipe): InferCurriedFromRecipe<183 Recipe,184 false185 >186187 /** Curried producer that infers curried from the State generic, which is explicitly passed in. */188 <State>(189 recipe: (190 state: Draft<State>,191 initialState: State192 ) => ValidRecipeReturnType<State>193 ): (state?: State) => State194 <State, Args extends any[]>(195 recipe: (196 state: Draft<State>,197 ...args: Args198 ) => ValidRecipeReturnType<State>,199 initialState: State200 ): (state?: State, ...args: Args) => State201 <State>(recipe: (state: Draft<State>) => ValidRecipeReturnType<State>): (202 state: State203 ) => State204 <State, Args extends any[]>(205 recipe: (state: Draft<State>, ...args: Args) => ValidRecipeReturnType<State>206 ): (state: State, ...args: Args) => State207208 /** Curried producer with initial state, infers recipe from initial state */209 <State, Recipe extends Function>(210 recipe: Recipe,129 initialState: Immutable<T>130 ): <Base extends Immutable<T>>(131 base?: Base,132 ...rest: Tail<Params>133 ) => Produced<Base, ReturnType<Recipe>>211 initialState: State212 ): InferCurriedFromInitialStateAndRecipe<State, Recipe, false>213214 /** Promisified dormal producer */215 <Base, D = Draft<Base>>(216 base: Base,217 recipe: (draft: D) => Promise<ValidRecipeReturnType<D>>,218 listener?: PatchListener219 ): Promise<Base>220221 /** Normal producer */136 <Base, D = Draft<Base>, Return = void>(222 <Base, D = Draft<Base>>( // By using a default inferred D, rather than Draft<Base> in the recipe, we can override it.223 base: Base,138 recipe: (draft: D) => Return,224 recipe: (draft: D) => ValidRecipeReturnType<D>,225 listener?: PatchListener140 ): Produced<Base, Return>226 ): Base227}228229/**230 * Like `produce`, but instead of just returning the new state,
1 unmodified line
232 *233 * Like produce, this function supports currying234 */235export interface IProduceWithPatches {150 /** Curried producer */151 <152 Recipe extends (...args: any[]) => any,153 Params extends any[] = Parameters<Recipe>,154 T = Params[0]155 >(156 recipe: Recipe157 ): <Base extends Immutable<T>>(158 base: Base,159 ...rest: Tail<Params>160 ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]161 // ^ by making the returned type generic, the actual type of the passed in object is preferred162 // over the type used in the recipe. However, it does have to satisfy the immutable version used in the recipe163 // 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!164165 /** Curried producer with initial state */166 <167 Recipe extends (...args: any[]) => any,168 Params extends any[] = Parameters<Recipe>,169 T = Params[0]170 >(236 // Types copied from IProduce, wrapped with PatchesTuple237 <Recipe extends AnyFunc>(recipe: Recipe): InferCurriedFromRecipe<Recipe, true>238 <State, Recipe extends Function>(239 recipe: Recipe,172 initialState: Immutable<T>173 ): <Base extends Immutable<T>>(174 base?: Base,175 ...rest: Tail<Params>176 ) => [Produced<Base, ReturnType<Recipe>>, Patch[], Patch[]]177178 /** Normal producer */179 <Base, D = Draft<Base>, Return = void>(240 initialState: State241 ): InferCurriedFromInitialStateAndRecipe<State, Recipe, true>242 <Base, D = Draft<Base>>(243 base: Base,181 recipe: (draft: D) => Return182 ): [Produced<Base, Return>, Patch[], Patch[]]244 recipe: (draft: D) => ValidRecipeReturnType<Base>,245 listener?: PatchListener246 ): PatchesTuple<Immutable<Base>>247 <Base, D = Draft<Base>>(248 base: Base,249 recipe: (draft: D) => Promise<ValidRecipeReturnType<Base>>,250 listener?: PatchListener251 ): PatchesTuple<Promise<Immutable<Base>>>252}253254// Fixes #507: bili doesn't export the types of this file if there is no actual source in it..255// hopefully it get's tree-shaken away for everyone :)
1 unmodified line
modified:website/docs/return.mdx+4 added-1 removed
7 unmodified lines
8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>12</center> <details>12</center>13<details>14 <summary className="egghead-summary">15 egghead.io lesson 9: Returning completely new state16 </summary>17 <br />
93 unmodified lines
111```112113N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.114115Tip: to be able to return `nothing` from a recipe when using TypeScript, the `state`'s type must accept `undefined` as value.116117## Inline shortcuts using `void`118119<details>120 <summary className="egghead-summary">
32 unmodified lines
modified:website/docs/typescript.mdx+83 added-18 removed
8 unmodified lines
9 data-ea-publisher="immerjs"10 data-ea-type="image"11 className="horizontal bordered"12 ></div>13</center> <details>13</center>14<details>15 <summary className="egghead-summary">16 egghead.io lesson 12: Immer + TypeScript17 </summary>18 <br />
36 unmodified lines
5556// `newState.x` cannot be modified here57```5858This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`!59This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`.6060For curried reducers, the type is inferred from the first argument of recipe function, so make sure to type it. The `Draft` utility type can be used if the state argument type is immutable:61## Best practices6262```ts63import produce, {Draft} from "immer"631. Always define your states as `readonly` as much as possible. This best reflects the mental model and reality, since Immer will freeze all its returned values.642. You can use the utility type `Immutable` to recursively make an entire type tree read-only, e.g.: `type ReadonlyState = Immutable<State>`.653. Immer won't automatically wrap all returned types in `Immutable` if the original type of the input state wasn't immutable. This is to make sure it doesn't break code bases that don't use immutable types.6665interface State {66 readonly x: number67}67## Tips for curried producers6869// `x` cannot be modified here70const state: State = {71 x: 072}69We try to inference as much as possible. So if a curried producer is created and directly passed to another function, we can infer the type from there. This works will with for example React:7074const increment = produce((draft: Draft<State>, inc: number) => {75 // `x` can be modified here76 draft.x += inc71```typescript72import {Immutable, produce} from "immer"7374type Todo = Immutable<{75 title: string76 done: boolean77}>7879// later...8081const [todo, setTodo] = useState<Todo>({82 title: "test",83 done: true84})8579const newState = increment(state, 2)80// `newState.x` cannot be modified here86// later...8788setTodo(89 produce(draft => {90 // draft will be strongly typed and mutable!91 draft.done = !draft.done92 })93)94```9583_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)_96When a curried producer isn't passed directly somewhere else, Immer can infer the state type from the draft argument. For example when doing the following:9798```typescript99// See below for a better solution!100101const toggler = produce((draft: Draft<Todo>) => {102 draft.done = !draft.done103})104105// typeof toggler = (state: Immutable<Todo>) => Writable<Todo>106```107108Note that we did wrap the `Todo` type of the `draft` argument with `Draft`, because `Todo` is a readonly type. For non-readonly types this isn't needed.109110For the returned curried function, `toggler`, We will _narrow_ the _input_ type to `Immutable<Todo>`, so that even though `Todo` is a mutable type, we will still accept an immutable todo as input argument to `toggler`.111112In contrast, Immer will _widen_ the _output_ type of the curried function to `Writable<Todo>`, to make sure it's output state is also assignable to variables that are not explictly typed to be immutable.113114This type narrowing / widening behavior might be unwelcome, maybe even for the simpe reason that it results in quite noisy types. So we recommend to specify the generic state type for curried producers instead, in cases where it cannot be inferred directly, like `toggler` above. By doing so the automatic output widening / input narrowing will be skipped. However, the `draft` argument itself will still be inferred to be a writable `Draft<Todo>`:115116```typescript117const toggler = produce<Todo>(draft => {118 draft.done = !draft.done119})120121// typeof toggler = (state: Todo) => Todo122```123124However, in case the curried producer is defined with an initial state, Immer can infer the state type from the initial state, so in that case the generic doesn't need to be specified either:125126```typescript127const state0: Todo = {128 title: "test",129 done: false130}131132// No type annotations needed, since we can infer from state0.133const toggler = produce(draft => {134 draft.done = !draft.done135}, state0)136137// typeof toggler = (state: Todo) => Todo138```139140In case the toggler has no initial state, and it has curried arguments, and you set the state generic explicitly, then type of any additional arguments should be defined explicitly as a tuple type as well:141142```typescript143const toggler = produce<Todo, [boolean]>((draft, newState) => {144 draft.done = newState145})146147// typeof toggler = (state: Todo, newState: boolean) => Todo148```149150## Cast utilities151152The 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`.153
58 unmodified lines
modified:package.json+2 added-2 removed
1{2 "name": "immer",3 "version": "7.0.0-beta.0",3 "version": "9.0.0-beta.1",4 "description": "Create your next immutable state by mutating the current one",5 "main": "dist/index.js",6 "module": "dist/immer.esm.js",7 "umd:main": "dist/immer.umd.production.min.js",
83 unmodified lines
91 "semantic-release": "^17.0.2",92 "spec.ts": "^1.1.0",93 "ts-jest": "^25.2.0",94 "tsdx": "^0.12.3",95 "typescript": "^3.9.3",95 "typescript": "^4.2.3",96 "webpack": "^4.41.6",97 "webpack-cli": "^3.3.11"98 }99}
modified:yarn.lock+4 added-12 removed
8501 unmodified lines
8502 cli-table3 "^0.5.1"8503 cmd-shim "^3.0.3"8504 columnify "~1.5.4"8505 config-chain "^1.1.12"8506 debuglog "*"8506 detect-indent "~5.0.0"8507 detect-newline "^2.1.0"8508 dezalgo "~1.0.3"8509 editor "~1.0.0"
6 unmodified lines
8516 graceful-fs "^4.2.4"8517 has-unicode "~2.0.1"8518 hosted-git-info "^2.8.8"8519 iferr "^1.0.2"8521 imurmurhash "*"8520 infer-owner "^1.0.4"8521 inflight "~1.0.6"8522 inherits "^2.0.4"8523 ini "^1.3.5"
10 unmodified lines
8534 libnpmteam "^1.0.2"8535 libnpx "^10.2.4"8536 lock-verify "^2.1.0"8537 lockfile "^1.0.4"8540 lodash._baseindexof "*"8538 lodash._baseuniq "~4.6.0"8542 lodash._bindcallback "*"8543 lodash._cacheindexof "*"8544 lodash._createcache "*"8545 lodash._getnative "*"8539 lodash.clonedeep "~4.5.0"8547 lodash.restparam "*"8540 lodash.union "~4.6.0"8541 lodash.uniq "~4.5.0"8542 lodash.without "~4.4.0"8543 lru-cache "^5.1.1"
3195 unmodified lines
11739 version "3.7.5"11740 resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.7.5.tgz#0692e21f65fd4108b9330238aac11dd2e177a1ae"11741 integrity sha512-/P5lkRXkWHNAbcJIiHPfRoKqyd7bsyCma1hZNUGfn20qm64T6ZBlrzprymeu918H+mB/0rIg2gGK/BXkhhYgBw==1174211751typescript@^3.9.3:11752 version "3.9.3"11753 resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.9.3.tgz#d3ac8883a97c26139e42df5e93eeece33d610b8a"11754 integrity sha512-D/wqnB2xzNFIcoBG9FG8cXRDjiqSTbG2wd8DMZeQyJlP1vfTkIxH4GKveWaEBYySKIg+USu+E+EDIR47SqnaMQ==11743typescript@^4.2.3:11744 version "4.2.3"11745 resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.2.3.tgz#39062d8019912d43726298f09493d598048c1ce3"11746 integrity sha512-qOcYwxaByStAWrBf4x0fibwZvMRG+r4cQoTjbPtUlrWjBHbmCAww1i448U0GJ+3cNNEtebDteo/cHOR3xJ4wEw==1174711748uglify-js@^3.1.4:11749 version "3.7.7"11750 resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.7.7.tgz#21e52c7dccda80a53bf7cde69628a7e511aec9c9"
739 unmodified lines