Skip to content
Myr

produce.ts

This file

Path

__tests__/produce.ts

844 lines · 18.0 KiB · TypeScript

Last changed by

fix: correct curried produceWithPatches return type (#1249)Alexander Kireyevbefore adoptiona3be9df

History of this file

Take it

1import {assert, _} from "./spec_ts"2import {3	produce,4	applyPatches,5	Patch,6	nothing,7	Draft,8	Immutable,9	Immer,10	enableMapSet,11	enablePatches,12	produceWithPatches13} from "../src/immer"1415enableMapSet()16enablePatches()1718interface State {19	readonly num: number20	readonly foo?: string21	bar: string22	readonly baz: {23		readonly x: number24		readonly y: number25	}26	readonly arr: ReadonlyArray<{readonly value: string}>27	readonly arr2: {readonly value: string}[]28}2930const state: State = {31	num: 0,32	bar: "foo",33	baz: {34		x: 1,35		y: 236	},37	arr: [{value: "asdf"}],38	arr2: [{value: "asdf"}]39}4041const expectedState: State = {42	num: 1,43	foo: "bar",44	bar: "foo",45	baz: {46		x: 2,47		y: 348	},49	arr: [{value: "foo"}, {value: "asf"}],50	arr2: [{value: "foo"}, {value: "asf"}]51}5253it("can update readonly state via standard api", () => {54	const newState = produce(state, draft => {55		draft.num++56		draft.foo = "bar"57		draft.bar = "foo"58		draft.baz.x++59		draft.baz.y++60		draft.arr[0].value = "foo"61		draft.arr.push({value: "asf"})62		draft.arr2[0].value = "foo"63		draft.arr2.push({value: "asf"})64	})65	assert(newState, _ as State)66})6768// NOTE: only when the function type is inferred69it("can infer state type from default state", () => {70	type State = {readonly a: number}71	type Recipe = (state?: State | undefined) => State7273	let foo = produce((_: any) => {}, _ as State)74	assert(foo, _ as Recipe)75})7677it("can infer state type from recipe function", () => {78	type A = {readonly a: string}79	type B = {readonly b: string}80	type State = A | B81	type Recipe = (state: State) => State8283	let foo = produce((draft: State) => {84		assert(draft, _ as State)85		if (Math.random() > 0.5) return {a: "test"}86		else return {b: "boe"}87	})88	const x = foo({a: ""})89	const y = foo({b: ""})90	assert(foo, _ as Recipe)91})9293it("can infer state type from recipe function with arguments", () => {94	type State = {readonly a: string} | {readonly b: string}95	type Recipe = (state: State, x: number) => State9697	let foo = produce<State, [number]>((draft, x) => {98		assert(draft, _ as Draft<State>)99		assert(x, _ as number)100	})101	assert(foo, _ as Recipe)102})103104it("can infer state type from recipe function with arguments and initial state", () => {105	type State = {readonly a: string} | {readonly b: string}106	type Recipe = (state: State | undefined, x: number) => State107108	let foo = produce((draft: Draft<State>, x: number) => {}, _ as State)109	assert(foo, _ as Recipe)110})111112it("cannot infer state type when the function type and default state are missing", () => {113	type Recipe = <S extends any>(state: S) => S114	const foo = produce((_: any) => {})115	// @ts-expect-error116	assert(foo, _ as Recipe)117})118119it("can update readonly state via curried api", () => {120	const newState = produce((draft: Draft<State>) => {121		draft.num++122		draft.foo = "bar"123		draft.bar = "foo"124		draft.baz.x++125		draft.baz.y++126		draft.arr[0].value = "foo"127		draft.arr.push({value: "asf"})128		draft.arr2[0].value = "foo"129		draft.arr2.push({value: "asf"})130	})(state)131	expect(newState).not.toBe(state)132	expect(newState).toEqual(expectedState)133})134135it("can update use the non-default export", () => {136	const newState = produce((draft: Draft<State>) => {137		draft.num++138		draft.foo = "bar"139		draft.bar = "foo"140		draft.baz.x++141		draft.baz.y++142		draft.arr[0].value = "foo"143		draft.arr.push({value: "asf"})144		draft.arr2[0].value = "foo"145		draft.arr2.push({value: "asf"})146	})(state)147	expect(newState).not.toBe(state)148	expect(newState).toEqual(expectedState)149})150151it("can apply patches", () => {152	let patches: Patch[] = []153	produce(154		{x: 3},155		d => {156			d.x++157		},158		p => {159			patches = p160		}161	)162163	expect(applyPatches({}, patches)).toEqual({x: 4})164})165166it("can apply readonly patches", () => {167	const [, patches]: readonly [168		{169			x: number170		},171		readonly Patch[],172		readonly Patch[]173	] = produceWithPatches({x: 3}, d => {174		d.x++175	})176177	expect(applyPatches({}, patches)).toEqual({x: 4})178})179180describe("curried producer", () => {181	it("supports rest parameters", () => {182		type State = {readonly a: 1}183184		// No initial state:185		{186			type Recipe = (state: State, a: number, b: number) => State187			let foo = produce((s: State, a: number, b: number) => {})188			assert(foo, _ as Recipe)189			foo(_ as State, 1, 2)190191			// @ts-expect-error192			foo(undefined, 1, 2)193		}194195		// Using argument parameters:196		{197			type Recipe = (state: Immutable<State>, ...rest: number[]) => Draft<State>198			let woo = produce((state: Draft<State>, ...args: number[]) => {})199			assert(woo, _ as Recipe)200			woo(_ as State, 1, 2)201		}202203		// With initial state:204		{205			type Recipe = (state?: State | undefined, ...rest: number[]) => State206			let bar = produce(207				(state: Draft<State>, ...args: number[]) => {},208				_ as State209			)210			assert(bar, _ as Recipe)211			bar(_ as State, 1, 2)212			bar(_ as State)213			bar()214		}215216		// When args is a tuple:217		{218			type Recipe = (219				state: State | undefined,220				first: string,221				...rest: number[]222			) => State223			let tup = produce(224				(state: Draft<State>, ...args: [string, ...number[]]) => {},225				_ as State226			)227			assert(tup, _ as Recipe)228			tup({a: 1}, "", 2)229			tup(undefined, "", 2)230		}231	})232233	it("can be passed a readonly array", () => {234		// No initial state:235		{236			let foo = produce((state: string[]) => {})237			assert(foo, _ as (state: readonly string[]) => string[])238			foo([] as ReadonlyArray<string>)239		}240241		// With initial state:242		{243			let bar = produce(() => {}, [] as ReadonlyArray<string>)244			assert(245				bar,246				_ as (state?: readonly string[] | undefined) => readonly string[]247			)248			bar([] as ReadonlyArray<string>)249			bar(undefined)250			bar()251		}252	})253})254255it("works with return type of: number", () => {256	let base = {a: 0} as {a: number}257	{258		if (Math.random() === 100) {259			// @ts-expect-error, this return accidentally a number, this is probably a dev error!260			let result = produce(base, draft => draft.a++)261		}262	}263	{264		let result = produce(base, draft => void draft.a++)265		assert(result, _ as {a: number})266	}267})268269it("can return an object type that is identical to the base type", () => {270	let base = {a: 0} as {a: number}271	let result = produce(base, draft => {272		return draft.a < 0 ? {a: 0} : undefined273	})274	assert(result, _ as {a: number})275})276277it("can NOT return an object type that is _not_ assignable to the base type", () => {278	let base = {a: 0} as {a: number}279	// @ts-expect-error280	let result = produce(base, draft => {281		return draft.a < 0 ? {a: true} : undefined282	})283})284285it("does not enforce immutability at the type level", () => {286	let result = produce([] as any[], draft => {287		draft.push(1)288	})289	assert(result, _ as any[])290})291292it("can produce an undefined value", () => {293	type State = {readonly a: number} | undefined294	const base = {a: 0} as State295296	// Return only nothing.297	let result = produce(base, _ => nothing)298	assert(result, _ as State)299300	// Return maybe nothing.301	let result2 = produce(base, draft => {302		if (draft?.a ?? 0 > 0) return nothing303	})304	assert(result2, _ as State)305})306307it("can return the draft itself", () => {308	let base = _ as {readonly a: number}309	let result = produce(base, draft => draft)310311	assert(result, _ as {readonly a: number})312})313314it("works with `void` hack", () => {315	let base = {a: 0} as {readonly a: number}316	let copy = produce(base, s => void s.a++)317	assert(copy, base)318})319320it("works with generic parameters", () => {321	let insert = <T>(array: readonly T[], index: number, elem: T) => {322		// Need explicit cast on draft as T[] is wider than readonly T[]323		return produce(array, (draft: T[]) => {324			draft.push(elem)325			draft.splice(index, 0, elem)326			draft.concat([elem])327		})328	}329	let val: {readonly a: ReadonlyArray<number>} = {a: []} as any330	let arr: ReadonlyArray<typeof val> = [] as any331	insert(arr, 0, val)332})333334it("can work with non-readonly base types", () => {335	const state = {336		price: 10,337		todos: [338			{339				title: "test",340				done: false341			}342		]343	}344	type State = typeof state345346	const newState = produce(state, draft => {347		draft.price += 5348		draft.todos.push({349			title: "hi",350			done: true351		})352	})353	assert(newState, _ as State)354355	const reducer = (draft: State) => {356		draft.price += 5357		draft.todos.push({358			title: "hi",359			done: true360		})361	}362363	// base case for with-initial-state364	const newState4 = produce(reducer, state)(state)365	assert(newState4, _ as State)366	// no argument case, in that case, immutable version recipe first arg will be inferred367	const newState5 = produce(reducer, state)()368	assert(newState5, _ as State)369	// we can force the return type of the reducer by casting the initial state370	const newState3 = produce(reducer, state as State)()371	assert(newState3, _ as State)372})373374it("can work with readonly base types", () => {375	type State = {376		readonly price: number377		readonly todos: readonly {378			readonly title: string379			readonly done: boolean380		}[]381	}382383	const state: State = {384		price: 10,385		todos: [386			{387				title: "test",388				done: false389			}390		]391	}392393	const newState = produce(state, draft => {394		draft.price + 5395		draft.todos.push({396			title: "hi",397			done: true398		})399	})400	assert(newState, _ as State)401	assert(newState, _ as Immutable<State>) // cause that is the same!402403	const reducer = (draft: Draft<State>) => {404		draft.price += 5405		draft.todos.push({406			title: "hi",407			done: true408		})409	}410	const newState2: State = produce(reducer)(state)411	assert(newState2, _ as State)412413	// base case for with-initial-state414	const newState4 = produce(reducer, state)(state)415	assert(newState4, _ as State)416	// no argument case, in that case, immutable version recipe first arg will be inferred417	const newState5 = produce(reducer, state)()418	assert(newState5, _ as State)419	// we can force the return type of the reducer by casting initial argument420	const newState3 = produce(reducer, state as State)()421	assert(newState3, _ as State)422})423424it("works with generic array", () => {425	const append = <T>(queue: T[], item: T) =>426		// T[] is needed here v. Too bad.427		produce(queue, (queueDraft: T[]) => {428			queueDraft.push(item)429		})430431	const queueBefore = [1, 2, 3]432433	const queueAfter = append(queueBefore, 4)434435	expect(queueAfter).toEqual([1, 2, 3, 4])436	expect(queueBefore).toEqual([1, 2, 3])437})438439it("works with Map and Set", () => {440	const m = new Map([["a", {x: 1}]])441	const s = new Set([{x: 2}])442443	const res1 = produce(m, draft => {444		assert(draft, _ as Map<string, {x: number}>)445	})446	assert(res1, _ as Map<string, {x: number}>)447448	const res2 = produce(s, draft => {449		assert(draft, _ as Set<{x: number}>)450	})451	assert(res2, _ as Set<{x: number}>)452})453454it("works with readonly Map and Set", () => {455	type S = {readonly x: number}456	const m: ReadonlyMap<string, S> = new Map([["a", {x: 1}]])457	const s: ReadonlySet<S> = new Set([{x: 2}])458459	const res1 = produce(m, (draft: Draft<Map<string, S>>) => {460		assert(draft, _ as Map<string, {x: number}>)461	})462	assert(res1, _ as ReadonlyMap<string, {readonly x: number}>)463464	const res2 = produce(s, (draft: Draft<Set<S>>) => {465		assert(draft, _ as Set<{x: number}>)466	})467	assert(res2, _ as ReadonlySet<{readonly x: number}>)468})469470it("works with ReadonlyMap and ReadonlySet", () => {471	type S = {readonly x: number}472	const m: ReadonlyMap<string, S> = new Map([["a", {x: 1}]])473	const s: ReadonlySet<S> = new Set([{x: 2}])474475	const res1 = produce(m, (draft: Draft<Map<string, S>>) => {476		assert(draft, _ as Map<string, {x: number}>)477	})478	assert(res1, _ as ReadonlyMap<string, {readonly x: number}>)479480	const res2 = produce(s, (draft: Draft<Set<S>>) => {481		assert(draft, _ as Set<{x: number}>)482	})483	assert(res2, _ as ReadonlySet<{readonly x: number}>)484})485486it("shows error in production if called incorrectly", () => {487	expect(() => {488		debugger489		produce(null as any)490	}).toThrow(491		(global as any).USES_BUILD492			? "[Immer] minified error nr: 6"493			: "[Immer] The first or second argument to `produce` must be a function"494	)495})496497it("#749 types Immer", () => {498	const t = {499		x: 3500	}501502	const immer = new Immer()503	const z = immer.produce(t, d => {504		d.x++505		// @ts-expect-error506		d.y = 0507	})508	expect(z.x).toBe(4)509	// @ts-expect-error510	expect(z.z).toBeUndefined()511})512513it("infers draft, #720", () => {514	function nextNumberCalculator(fn: (base: number) => number) {515		// noop516	}517518	const res2 = nextNumberCalculator(519		produce(draft => {520			// @ts-expect-error521			let x: string = draft522			return draft + 1523		})524	)525526	const res = nextNumberCalculator(527		produce(draft => {528			// @ts-expect-error529			let x: string = draft530			// return draft + 1;531			return undefined532		})533	)534})535536it("infers draft, #720 - 2", () => {537	function useState<S>(538		initialState: S | (() => S)539	): [S, Dispatch<SetStateAction<S>>] {540		return [initialState, function () {}] as any541	}542	type Dispatch<A> = (value: A) => void543	type SetStateAction<S> = S | ((prevState: S) => S)544545	const [n, setN] = useState({x: 3})546547	setN(548		produce(draft => {549			// @ts-expect-error550			draft.y = 4551			draft.x = 5552			return draft553		})554	)555556	setN(557		produce(draft => {558			// @ts-expect-error559			draft.y = 4560			draft.x = 5561			// return draft + 1;562			return undefined563		})564	)565566	setN(567		produce(draft => {568			return {y: 3} as const569		})570	)571})572573it("infers draft, #720 - 3", () => {574	function useState<S>(575		initialState: S | (() => S)576	): [S, Dispatch<SetStateAction<S>>] {577		return [initialState, function () {}] as any578	}579	type Dispatch<A> = (value: A) => void580	type SetStateAction<S> = S | ((prevState: S) => S)581582	const [n, setN] = useState({x: 3} as {readonly x: number})583584	setN(585		produce(draft => {586			// @ts-expect-error587			draft.y = 4588			draft.x = 5589			return draft590		})591	)592593	setN(594		produce(draft => {595			// @ts-expect-error596			draft.y = 4597			draft.x = 5598			// return draft + 1;599			return undefined600		})601	)602603	setN(604		produce(draft => {605			return {y: 3} as const606		})607	)608})609610it("infers curried", () => {611	type Todo = {title: string}612	{613		const fn = produce((draft: Todo) => {614			let x: string = draft.title615		})616617		fn({title: "test"})618		// @ts-expect-error619		fn(3)620	}621	{622		const fn = produce((draft: Todo) => {623			let x: string = draft.title624			return draft625		})626627		fn({title: "test"})628		// @ts-expect-error629		fn(3)630	}631})632633{634	type State = {count: number}635	type ROState = Immutable<State>636	const base: any = {count: 0}637	{638		// basic639		const res = produce(base as State, draft => {640			draft.count++641		})642		assert(res, _ as State)643	}644	{645		// basic646		const res = produce<State>(base, draft => {647			draft.count++648		})649		assert(res, _ as State)650	}651	{652		// basic653		const res = produce(base as ROState, draft => {654			draft.count++655		})656		assert(res, _ as ROState)657	}658	{659		// curried660		const f = produce((state: State) => {661			state.count++662		})663		assert(f, _ as (state: Immutable<State>) => State)664	}665	{666		// curried667		const f = produce((state: Draft<ROState>) => {668			state.count++669		})670		assert(f, _ as (state: ROState) => State)671	}672	{673		// curried674		const f: (value: State) => State = produce(state => {675			state.count++676		})677	}678	{679		// curried680		const f: (value: ROState) => ROState = produce(state => {681			state.count++682		})683	}684	{685		// curried initial686		const f = produce(state => {687			state.count++688		}, _ as State)689		assert(f, _ as (state?: State) => State)690	}691	{692		// curried initial693		const f = produce(state => {694			state.count++695		}, _ as ROState)696		assert(f, _ as (state?: ROState) => ROState)697	}698	{699		// curried700		const f: (value: State) => State = produce(state => {701			state.count++702		}, base as ROState)703	}704	{705		// curried706		const f: (value: ROState) => ROState = produce(state => {707			state.count++708		}, base as ROState)709	}710	{711		// nothing allowed712		const res = produce(base as State | undefined, draft => {713			return nothing714		})715		assert(res, _ as State | undefined)716	}717	{718		// as any719		const res = produce(base as State, draft => {720			return nothing as any721		})722		assert(res, _ as State)723	}724	{725		// nothing not allowed726		// @ts-expect-error727		produce(base as State, draft => {728			return nothing729		})730	}731	{732		const f = produce((draft: State) => {})733		const n = f(base as State)734		assert(n, _ as State)735	}736	{737		const f = produce((draft: Draft<ROState>) => {738			draft.count++739		})740		const n = f(base as ROState)741		assert(n, _ as State)742	}743	{744		// explicitly use generic745		const f = produce<ROState>(draft => {746			draft.count++747		})748		const n = f(base as ROState)749		assert(n, _ as ROState) // yay!750	}751	{752		// explicitly use generic, but curried753		const f = produce<ROState>(draft => {754			draft.count++755		})756		assert(f, _ as (state: ROState) => ROState)757	}758	// produceWithPatches should infer the same state type as produce (#1045),759	// just wrapped in the [state, patches, inversePatches] tuple760	{761		// curried762		const f = produceWithPatches((state: State) => {763			state.count++764		})765		assert(766			f,767			_ as (state: Immutable<State>) => readonly [State, Patch[], Patch[]]768		)769	}770	{771		// curried, with extra argument772		const f = produceWithPatches((state: State, delta: number) => {773			state.count += delta774		})775		assert(776			f,777			_ as (778				state: Immutable<State>,779				delta: number780			) => readonly [State, Patch[], Patch[]]781		)782	}783	{784		// explicitly use generic, but curried785		const f = produceWithPatches<State, [number]>((state, delta) => {786			state.count += delta787		})788		assert(789			f,790			_ as (state: State, delta: number) => readonly [State, Patch[], Patch[]]791		)792	}793}794795it("allows for mixed property value types", () => {796	type TestReadonlyObject = {797		readonly testObjectOrNull: {readonly testProperty: number} | null798	}799800	const input: TestReadonlyObject = {testObjectOrNull: null}801802	produce(input, draft => {803		if (draft.testObjectOrNull) {804			draft.testObjectOrNull.testProperty = 5805		}806	})807})808809it("allows higher order type inference", () => {810	function _test<A>() {811		type S = {prop: A | undefined}812		produce(813			draft => {814				draft.prop = undefined815			},816			{prop: undefined} as S817		)818	}819})820821it("supports tuples with spread", () => {822	type State = [boolean, ...number[]]823	const foo = (x: State) => x824	produce<State>(x => foo(x))825})826827it("#877 - produce with typed state generic requires initial state", () => {828	const reducerNoInitial = produce<{count: number}, [{type: "inc"}]>(829		(draft, action: {type: "inc"}) => {830			if (action.type === "inc") draft.count++831		}832	)833	const reducer = produce<{count: number}, [{type: "inc"}]>(834		(draft, action: {type: "inc"}) => {835			if (action.type === "inc") draft.count++836		},837		{count: 0}838	)839840	expect(reducer({count: 0}, {type: "inc"})).toEqual({count: 1})841	expect(reducer(undefined, {type: "inc"})).toEqual({count: 1})842	// @ts-expect-error runtime error without initial state843	expect(() => reducerNoInitial(undefined, {type: "inc"})).toThrow()844})