Skip to content

Commit 0c6e308

Browse files
committed
fix: JSON.parse accepts readonly arrays
closes #1
1 parent f110671 commit 0c6e308

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

lib/lib.es5.d.ts

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,16 @@ type JSONValue =
209209
}
210210
| JSONValue[];
211211

212+
type ReadonlyJSONValue =
213+
| null
214+
| string
215+
| number
216+
| boolean
217+
| {
218+
readonly [K in string]?: ReadonlyJSONValue;
219+
}
220+
| readonly ReadonlyJSONValue[];
221+
212222
interface JSON {
213223
/**
214224
* Converts a JavaScript Object Notation (JSON) string into an object.
@@ -227,8 +237,12 @@ interface JSON {
227237
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
228238
*/
229239
stringify(
230-
value: JSONValue,
231-
replacer?: (this: JSONValue, key: string, value: JSONValue) => any,
240+
value: ReadonlyJSONValue,
241+
replacer?: (
242+
this: ReadonlyJSONValue,
243+
key: string,
244+
value: ReadonlyJSONValue
245+
) => any,
232246
space?: string | number
233247
): string;
234248
/**
@@ -238,7 +252,7 @@ interface JSON {
238252
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
239253
*/
240254
stringify(
241-
value: JSONValue,
255+
value: ReadonlyJSONValue,
242256
replacer?: (number | string)[] | null,
243257
space?: string | number
244258
): string;

tests/es5.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,17 @@ expectType<{ foo: number; bar: string; baz: boolean }>(
7878
})();
7979

8080
// JSON
81-
expectType<JSONValue>(JSON.parse("{}"));
81+
{
82+
expectType<JSONValue>(JSON.parse("{}"));
83+
const arr = [1, 2, "foo"];
84+
expectType<string>(JSON.stringify(arr));
85+
const obj = { foo: { bar: 1 } };
86+
expectType<string>(JSON.stringify(obj));
87+
const readonlyArr = [1, 2, 3] as const;
88+
expectType<string>(JSON.stringify(readonlyArr));
89+
const readonlyObj = { foo: { bar: 1 } } as const;
90+
expectType<string>(JSON.stringify(readonlyObj));
91+
}
8292

8393
// ArrayConstructor
8494
{

0 commit comments

Comments
 (0)