UNPKG

1.03 kBTypeScriptView Raw
1import type {JsonPrimitive} from './basic';
2
3type JsonifiableObject = {[Key in string]?: Jsonifiable} | {toJSON: () => Jsonifiable};
4type JsonifiableArray = readonly Jsonifiable[];
5
6/**
7Matches a value that can be losslessly converted to JSON.
8
9Can be used to type values that you expect to pass to `JSON.stringify`.
10
11`undefined` is allowed in object fields (for example, `{a?: number}`) as a special case even though `JSON.stringify({a: undefined})` is `{}` because it makes this class more widely useful and checking for undefined-but-present values is likely an anti-pattern.
12
13@example
14```
15import type {Jsonifiable} from 'type-fest';
16
17// @ts-expect-error
18const error: Jsonifiable = {
19 map: new Map([['a', 1]]),
20};
21
22JSON.stringify(error);
23//=> {"map": {}}
24
25const good: Jsonifiable = {
26 number: 3,
27 date: new Date(),
28 missing: undefined,
29}
30
31JSON.stringify(good);
32//=> {"number": 3, "date": "2022-10-17T22:22:35.920Z"}
33```
34
35@category JSON
36*/
37export type Jsonifiable = JsonPrimitive | JsonifiableObject | JsonifiableArray;