Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Jsonify: Convert undefined to null in union element of array #901

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion source/jsonify.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {UnknownArray} from './unknown-array';
type NotJsonable = ((...arguments_: any[]) => any) | undefined | symbol;

type NeverToNull<T> = IsNever<T> extends true ? null : T;
type UndefinedToNull<T> = T extends undefined ? null : T;

// Handles tuples and arrays
type JsonifyList<T extends UnknownArray> = T extends readonly []
Expand All @@ -20,7 +21,7 @@ type JsonifyList<T extends UnknownArray> = T extends readonly []
? [NeverToNull<Jsonify<F>>, ...JsonifyList<R>]
: IsUnknown<T[number]> extends true
? []
: Array<T[number] extends NotJsonable ? null : Jsonify<T[number]>>;
: Array<T[number] extends NotJsonable ? null : Jsonify<UndefinedToNull<T[number]>>>;

type FilterJsonableKeys<T extends object> = {
[Key in keyof T]: T[Key] extends NotJsonable ? never : Key;
Expand Down
6 changes: 6 additions & 0 deletions test-d/jsonify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,12 @@ expectType<never>(plainSymbol);
declare const arrayMemberUndefined: Jsonify<Array<typeof undefined>>;
expectType<null[]>(arrayMemberUndefined);

declare const arrayMemberUnionWithUndefined: Jsonify<Array<typeof undefined | typeof number>>;
expectType<Array<null | number>>(arrayMemberUnionWithUndefined);
sindresorhus marked this conversation as resolved.
Show resolved Hide resolved

declare const arrayMemberUnionWithUndefinedDeep: Jsonify<Array<Array<typeof undefined | typeof number>> | {foo: Array<typeof undefined | typeof number>}>;
expectType<Array<Array<null | number>> | {foo: Array<null | number>}>(arrayMemberUnionWithUndefinedDeep);

declare const arrayMemberFunction: Jsonify<Array<typeof function_>>;
expectType<null[]>(arrayMemberFunction);

Expand Down