Skip to content

Commit 031492d

Browse files
huytdps13400claude
andauthored
fix: avoid excessive Draft recursion for readonly arrays in recursive types (#1311)
WritableDraft only took the `Draft<T[number]>[]` shortcut for mutable arrays, so readonly arrays went through the mapped type and recursive types such as type-fest's JsonValue (which uses `readonly JsonValue[]`) still hit TS2589. Match `readonly any[]` so readonly plain arrays take the same path. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 4d37e43 commit 031492d

2 files changed

Lines changed: 19 additions & 2 deletions

File tree

‎__tests__/type-external.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import {isType, JSONArray, JSONObject, JSONTypes} from "type-plus"
22
import {Draft} from "../src/types/types-external"
3-
import {createDraft, current, original} from "../src/immer"
3+
import {createDraft, current, original, produce} from "../src/immer"
44

55
describe("Draft<T>", () => {
66
test("can use JSONTypes as T", () => {
@@ -17,6 +17,23 @@ describe("Draft<T>", () => {
1717
type A = Draft<[string, number, JSONArray, JSONObject]>
1818
isType.equal<true, [string, number, JSONArray, JSONObject], A>()
1919
})
20+
21+
it("can use recursive types containing readonly arrays as T (#839)", () => {
22+
// Same shape as type-fest's JsonValue
23+
type JsonValue = string | number | boolean | null | JsonObject | JsonArray
24+
type JsonObject = {[Key in string]: JsonValue} & {
25+
[Key in string]?: JsonValue | undefined
26+
}
27+
type JsonArray = JsonValue[] | readonly JsonValue[]
28+
29+
type A = Draft<readonly JsonValue[]>
30+
isType.equal<true, Draft<JsonValue>[], A>()
31+
32+
const base: {readonly items: readonly JsonValue[]} = {items: []}
33+
produce(base, draft => {
34+
draft.items.push({a: [1, "b"]})
35+
})
36+
})
2037
})
2138

2239
describe("current() typings", () => {

‎src/types/types-external.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ export type IfAvailable<T, Fallback = void> =
2828
*/
2929
type WeakReferences = IfAvailable<WeakMap<any, any>> | IfAvailable<WeakSet<any>>
3030

31-
export type WritableDraft<T> = T extends any[]
31+
export type WritableDraft<T> = T extends readonly any[]
3232
? number extends T["length"]
3333
? IsPlainArray<T> extends true
3434
? Draft<T[number]>[]

0 commit comments

Comments
 (0)