Skip to content

Commit c8aa89a

Browse files
committed
Add types for shallow option
1 parent ad57c5d commit c8aa89a

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

src/main.d.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ export interface Options {
3030
}
3131

3232
type InvalidJSONValue = bigint | Function | undefined | symbol
33-
type ReturnValue<T> = T extends Array<infer ArrayItem>
34-
? Array<ReturnValue<ArrayItem>>
33+
type ReturnValue<T, Shallow extends boolean> = T extends Array<infer ArrayItem>
34+
? Array<Shallow extends true ? ArrayItem : ReturnValue<ArrayItem, Shallow>>
3535
: T extends InvalidJSONValue
3636
? undefined
3737
: T extends Date
@@ -42,7 +42,9 @@ type ReturnValue<T> = T extends Array<infer ArrayItem>
4242
? {
4343
[key in keyof T as T[key] extends InvalidJSONValue
4444
? never
45-
: Exclude<key, symbol>]?: ReturnValue<T[key]>
45+
: Exclude<key, symbol>]?: Shallow extends true
46+
? T[key]
47+
: ReturnValue<T[key], Shallow>
4648
}
4749
: T
4850

@@ -132,9 +134,9 @@ export type Change<ReasonValue extends Reason = Reason> = {
132134
* // ]
133135
* ```
134136
*/
135-
export default function safeJsonValue<T>(
137+
export default function safeJsonValue<T, OptionsArg extends Options = {}>(
136138
value: T,
137-
options?: Options,
139+
options?: OptionsArg,
138140
): {
139141
/**
140142
* Copy of the input `value` after applying all the changes to make
@@ -143,7 +145,9 @@ export default function safeJsonValue<T>(
143145
* The top-level `value` itself might be changed (including to `undefined`) if
144146
* it is either invalid JSON or has a `toJSON()` method.
145147
*/
146-
value: ReturnValue<T> | undefined
148+
value:
149+
| ReturnValue<T, OptionsArg['shallow'] extends true ? true : false>
150+
| undefined
147151

148152
/**
149153
* List of changes applied to `value`.

src/main.test-d.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,3 +112,12 @@ safeJsonValue('', { shallow: true })
112112
expectAssignable<Options>({ shallow: true })
113113
expectError(safeJsonValue('', { shallow: 'true' }))
114114
expectNotAssignable<Options>({ shallow: 'true' })
115+
116+
expectType<string | undefined>(safeJsonValue({ a: new Date() }).value?.a)
117+
expectType<Date | undefined>(
118+
safeJsonValue({ a: new Date() }, { shallow: true }).value?.a,
119+
)
120+
expectType<string | undefined>(safeJsonValue([new Date()]).value?.[0])
121+
expectType<Date | undefined>(
122+
safeJsonValue([new Date()], { shallow: true }).value?.[0],
123+
)

0 commit comments

Comments
 (0)