Skip to content

Commit 450c945

Browse files
committed
Add strong types for JSON.stringify
1 parent b21978d commit 450c945

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
interface JSON {
2+
/**
3+
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
4+
* @param value A JavaScript value, usually an object or array, to be converted.
5+
* @param replacer A function that transforms the results.
6+
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
7+
*/
8+
stringify<T = any>(
9+
value: T,
10+
replacer?: (this: any, key: string, value: any) => any,
11+
space?: string | number
12+
): undefined extends T ? string | undefined : string;
13+
/**
14+
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
15+
* @param value A JavaScript value, usually an object or array, to be converted.
16+
* @param replacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.
17+
* @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.
18+
*/
19+
stringify<T = any>(
20+
value: T,
21+
replacer?: (number | string)[] | null,
22+
space?: string | number
23+
): undefined extends T ? string | undefined : string;
24+
}

src/tests/json-stringify.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { doNotExecute, Equal, Expect } from "./utils";
2+
3+
doNotExecute(() => {
4+
const result = JSON.stringify(undefined);
5+
type tests = [Expect<Equal<typeof result, string | undefined>>];
6+
});
7+
8+
doNotExecute(() => {
9+
const result = JSON.stringify(5 as undefined | number);
10+
type tests = [Expect<Equal<typeof result, string | undefined>>];
11+
});
12+
13+
doNotExecute(() => {
14+
const result = JSON.stringify(undefined as any);
15+
type tests = [Expect<Equal<typeof result, string | undefined>>];
16+
});
17+
18+
doNotExecute(() => {
19+
const result = JSON.stringify(undefined as unknown);
20+
type tests = [Expect<Equal<typeof result, string | undefined>>];
21+
});
22+
23+
doNotExecute(() => {
24+
const value: null | string | number | boolean | object | Array<any> = null;
25+
const result = JSON.stringify(value);
26+
type tests = [Expect<Equal<typeof result, string>>];
27+
});

0 commit comments

Comments
 (0)