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: handle undefined in array. #310

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 8 additions & 1 deletion source/jsonify.d.ts
Expand Up @@ -3,6 +3,13 @@ import {JsonPrimitive, JsonValue} from './basic';
// Note: The return value has to be `any` and not `unknown` so it can match `void`.
type NotJsonable = ((...args: any[]) => any) | undefined;

// Note: Handles special case where Arrays with `undefined` are transformed to `'null'` by `JSON.stringify()`
// Only use with array members
type JsonifyArrayMember<T> =
T extends undefined ?
null | Exclude<T, undefined> :
Jsonify<T>;

/**
Transform a type to one that is assignable to the `JsonValue` type.

Expand Down Expand Up @@ -64,7 +71,7 @@ type Jsonify<T> =
? T extends JsonPrimitive
? T // Primitive is acceptable
: T extends Array<infer U>
? Array<Jsonify<U>> // It's an array: recursive call for its children
? Array<JsonifyArrayMember<U>> // It's an array: recursive call for its children
: T extends object
? T extends {toJSON(): infer J}
? (() => J) extends (() => JsonValue) // Is J assignable to JsonValue?
Expand Down
12 changes: 12 additions & 0 deletions test-d/jsonify.ts
Expand Up @@ -123,6 +123,18 @@ const nonJsonWithInvalidToJSON = new NonJsonWithInvalidToJSON();
expectNotAssignable<JsonValue>(nonJsonWithInvalidToJSON);
expectNotAssignable<JsonValue>(nonJsonWithInvalidToJSON.toJSON());

// Special cases of Array with `undefined` member
// `[undefined]` is not JSON because it contains non JSON value `undefined`
// However `JSON.parse(JSON.stringify())` transforms array members of `undefined` to `null`
expectNotAssignable<JsonValue>([undefined]);
declare const parsedStringifiedArrayWithUndefined1: Jsonify<undefined[]>; // = JSON.parse(JSON.stringify([undefined]));
expectType<null[]>(parsedStringifiedArrayWithUndefined1);
expectAssignable<JsonValue>(parsedStringifiedArrayWithUndefined1);
expectNotAssignable<JsonValue>([undefined, 1]);
declare const parsedStringifiedArrayWithUndefined2: Jsonify<[undefined, number]>;
expectType<Array<number | null>>(parsedStringifiedArrayWithUndefined2);
expectAssignable<JsonValue>(parsedStringifiedArrayWithUndefined2);

// Test that optional type members are not discarded wholesale.
interface OptionalPrimitive {
a?: string;
Expand Down